- creating a simple backend using express should look like below.
In the `server.js` ( or whatever file that runs on node)
import express from 'express'
// if importing as module, instead of commonJS, set property "type": "module" in package.json
const app = express();
app.get( '/' ,(req,res)=>{
res.send('server is ready')
})
app.get('/data', (req,res) => {
res.send('data.json')
// lets assume this route sends some json data
})
const port = process.env.PORT || 3000
// with an assumption that there is .env file
app.listen(port, () => {
console.log(`server is running on port ${port}`)
})
- create frontend with vite ( or any bunlder of your choice)
create vite@latest .
here
.
after the command creates the app in the root, without making subfolder.
- Let us assume we make a data request from one of the our components in React.
- There are many ways to request data from backend i.e., fetch, axios, reactQuert etc.
- Here we use axios, which has better functionality than fetch (we dont need to jsonIfy response in axios)
useEfffect(()=> {
axios.get('https://localhost:3000/data')
.then((response)=> {
setData(response.data)
})
.catch((error)=> {
console.log(error)
})
},[])
-
this request should would obviously give CORS Error, known reason that server and client are running on different servers/ports and those are not whitelisted
-
simple fix here would be to use the
cors
package
const cors = require("cors")
app.use(cors())
-
another practice would be to standardize the backend routes, instead of serving on
/data
, we make it/api/data
or/api/v1/data
-
also specifying the localhost in useEffect is also issue, when we move the application to production would fail.
- so lets modify the request url in useEffect, considering above two points
/api/data
- this would again give error, as there is no such url
- so lets modify the request url in useEffect, considering above two points
-
Here we implement a proxy to overcome this
- if the application is built using
create-react-app
we add"proxy": "https://localhost:3000"
insidepackage.json
.
- in case its
vite
application add below configuration tovite.config.js
server: { proxy: { "/api": { target: "https://localhost:3000", changeOrigin: true, secure: false, }, }, },
- here we proxy the frontend connection to same port as backend, which removes the cross-origin error. In simple terms all fron request that goto
/api
route will be proxied withtarget
- if the application is built using
- Setting up a proxy is only for development purpose, in production , we append the backend URL to the path
- As we are already handling cross origin request, it shouldn't cause any error
// for CRA
const API = process.env.API
// for Vite App (always start with VITE_)( dont store secrets here)
// as backend url is not a secret this approach is fine
const API = import.meta.env.VITE_API
axios.get('${API}/data')
API='https://backendurl.site.com`
VITE_API='https://backendurl.site.com`
we send the backend url string using environment variables
- set ENVs during deployment.
-useful links