Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRA 2.0 How to setup proxy in React?

In CRA 2.0 proxy property on the package.json does not work. After some research, I came across an article suggesting to use http-proxy-middleware. I created an setupProxy.js in the src of my client folder(React side). That contains the following code

const proxy = require("http-proxy-middleware");
module.exports = function(app) {
  console.log("Setup proxy is ever called");
  app.use(proxy("/api/auth/google", { target: "http://localhost:5000/" }));
};

What am I supposed to do after this. Where should I import the setupProxy.js file. From where it is gonna receive app.

like image 732
Unity Hour Avatar asked Nov 24 '18 06:11

Unity Hour


People also ask

How do I set up React proxy?

Using a manually created proxy in Create React App Ensure you don't have proxy defined in the package. json file, then create a new file named setupProxy. js in the src directory. Add the following code snippet to the setupProxy.

How do I add a proxy to React project?

Proxy Setup with Create-React-App All you have to do is add a proxy field to your package. json file, like shown below. "proxy": "http://localhost:3000", This line instructs the development server to proxy any unknown requests to your API server in development mode.

How add proxy to package json in React?

To configure the proxy, you'll need to add the following line to your package. json . Then, in your React app, you can make API requests by using relative paths. For example, http://localhost:8000/api/todos becomes /api/todos .

What is CRA in React?

Install and Launch CRA Create React App allows you to generate a skeleton code for your app. It includes some preconfigured tools such as Webpack, Babel, and ESLint to guarantee the best development experience. To manipulate Create React App, you're going to need a package manager on your terminal.


1 Answers

The proxy value in package.json does still work in CRA 2, but it now only accepts a string, more complicated proxy options have to be put in src/setupProxy.js as you are doing. But be careful, if you leave the proxy property in package.json CRA will use that and ignore your setupProxy.js file.

You don't need to import setupProxy.js anywhere, CRA will find it as long as it's in src.

Don't worry about where app comes from, that variable will be provided at runtime.

Your example will work, I've tried it (as long as you remove the old proxy string from package.json). But the console.log will not be logged to the terminal (I'm not sure why).

Further reading, the PR where this change was introduced: https://github.com/facebook/create-react-app/pull/5073

like image 174
jay_aye_see_kay Avatar answered Oct 11 '22 23:10

jay_aye_see_kay