Create React App http-proxy-middleware not working

Viewed 22772

So I've set up my proxies on my create-react-app application using http-proxy-middleware. I'm sure I've followed the instructions to the letter, but I keep getting a 404 every time I try to click the relevant link.

I'm using create-react-app v3.2.

Here's my setupProxy.js file:

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

module.exports = function(app) {
    app.use(proxy("/api", { target: "http://localhost:3090" }));
};

Here's the action creator that makes the http request

export const signIn = formProps => async dispatch => {
    try {
        const response = await axios.post("/api/login", formProps);

        //.....etc, etc
    } catch(e) {

        //.....etc,etc
    }
}

And here's the relevant route on my express server:

app.post("/login", requireSignIn, Authentication.login);

When the development server starts up, I get the following message:

[HPM] Proxy created: /api  -> http://localhost:3090

So setupProxy.js is obviously being picked up by CRA, but there's something wrong somewhere. I've tried adding wildcards to the proxy setup (e.g. "/api/*") but no luck. I get the following 404 logged in my console on the client side:

POST http://localhost:3000/api/login 404 (Not Found)

which refers to localhost:3000, suggesting that the proxy (which should redirect to localhost:3090) is not being used.

I can't help thinking that there's something really simple that I'm missing here, but currently tearing my hair out trying to get this to work.

Any help would be much appreciated.

Thanks!

3 Answers

As of v1.0.0 of http-proxy-middleware, the setupProxy.js file requires an explicit import; so instead of the previous default import

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

You need to use:

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
    app.use(createProxyMiddleware("/api", { target: "http://localhost:3090" }));
};

Found the answer to this one - and as expected it was a simple error.

The routes on my express server were as follows:

app.post("/login", requireSignIn, Authentication.login);

Whereas they should have been:

app.post("api/login", requireSignIn, Authentication.login);

Problem solved!

Replace codes of setupProxy.js file as follows:

const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
  app.use(
    '/api/login',
    createProxyMiddleware({
      target: 'http://localhost:3090',
      changeOrigin: true,
    })
  );
};
Related