React - Proxy to a backend

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

How to proxy request to a backend in React.

3 - Configuration

3.1 - 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:

package.json
"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.

Advertising

3.2 - 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

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

4 - Documentation / Reference

web/javascript/react/proxy.txt · Last modified: 2019/06/17 13:24 by gerardnico