React - Proxy to a backend

About

How to proxy request to a backend in React.

Configuration

Package.json

To tell the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json, for example:

"proxy": "http://localhost:4000"

This way, any unrecognized request without a text/html accept header will be redirected to the specified proxy.

For instance, when you fetch('/api/todos') in development (ie NODE_ENV=development), the development server will not find the resource and will proxy the request to http://localhost:4000/api/todos as a fallback.

http-proxy-middleware

The dev server of React is a Express app instance) and the proxy is based on http-proxy-middleware

You can set it up to get more proxy rules with the file src/setupProxy.js

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(proxy('/api', { target: 'http://localhost:5000/' }));
  // whatever that http-proxy-middleware accepts
};

See Node - http-proxy-middleware

Documentation / Reference





Discover More
What are possible backend integrations method? API , Multi Zone,

Frontend frameworks that manage the rendering of a page need to fill them with data that comes from an external API generally a Rest API. Possibilities Support different host Support same host Description...



Share this page:
Follow us:
Task Runner