Finally, we have to define a proxy, to make sure that we can request our API from the same Uniform Resource Locator (URL) as the client. This is needed because, otherwise, we would have to deal with cross-site requests, which are a bit more complicated to handle. We are going to define a proxy that will forward requests from http://localhost:3000/api/ to http://localhost:4000/.
Now, let's configure the proxy:
- First, we have to install the http-proxy-middleware package:
> npm install --save http-proxy-middleware
- Then, we create a new src/setupProxy.js file, with the following contents:
const proxy = require('http-proxy-middleware')
module.exports = function (app) {
app.use(proxy('/api', {
- Next, we have to define the target of our proxy, which will be the backend server, running at http://localhost:4000:
target: 'http://localhost:4000',
- Finally, we have to define a path-rewrite rule, which removes the /api prefix before forwarding the request to our server:
pathRewrite: { '^/api': '' }
}))
}
The preceding proxy configuration will link /api to our backend server; therefore, we can now start both the server and the client via the following command:
> npm start
Then, we can access the API by opening http://localhost:3000/api/posts/react-hooks!