subhro
subhro

Reputation: 85

setupProxy is not working - http-proxy-middleware

My react app is up on localhost:3000 and node server is running on localhost:5000. When I am trying to connect to the express API the route is going to 'localhost:3000/auth/google' instead of localhost:5000/auth/google

the error i am getting when trying to hit the express api

UserAction.js

export const updateLoginUser = (userData, scheme) => async dispatch => {
console.log(scheme);
if(scheme === 'google') {
    // TODO: fetch user from the DB
    const fetchedUser = await axios.post('/auth/google');
    dispatch({
        type: UPDATE_USER, 
        payload: fetchedUser.data
    })
} else {
    // TODO: fetch user from the DB
    const fetchedUser = await axios.post('/api/get_user/', {
        method: 'POST',
        headers: {
            'content-type': 'application/json'
        },
        body: JSON.stringify(userData)
    })
    dispatch({
        type: UPDATE_USER, 
        payload: fetchedUser.data
    })
}

}

setupProxy.js

 const proxy = require('http-proxy-middleware')
module.exports = function(app) {
    app.use(proxy('/auth/google', { target: 'http://localhost:5000' }))
}

NODE server.js

const express = require('express');
const mongoose = require('mongoose');
const keys = require('./config/keys');
const cookieSession = require('cookie-session');
const passport = require('passport');
const cors = require('cors');
const morgan = require('morgan');

require('./models/Users');
require('./services/passport'); // it is not returing anything hence no need of assigning

mongoose.connect(keys.mongoDBURI, { useNewUrlParser: true, useUnifiedTopology: true });

const app = express();
app.use(cors());

// Setup the cookie session
app.use(cookieSession({
    maxAge: 30 * 24 * 60 * 1000, // Time till the cookie will be alive
    keys: [keys.cookieKey]
}));


app.use(morgan('combined'));
// Make passport know to use the cookieSession
app.use(passport.initialize());
app.use(passport.session());

require('./routes/authRoutes')(app); // authRoute returing a function and we are immediatly invoking that function

const PORT = process.env.PORT || 5000;
app.listen(5000);

EDIT: react package.json

{
  "name": "blogpost-frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.19.0",
    "http-proxy-middleware": "^0.20.0",
    "node-sass": "^4.13.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-redux": "^7.1.3",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.2.0",
    "redux": "^4.0.4",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:5000"
}

I am new to this hence I do not know how exactly proxy works.

Upvotes: 3

Views: 17466

Answers (5)

Use pathFilter option to further include/exclude requests which you want to proxy.it work for me!

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

module.exports = function(app) {
    app.use(
      createProxyMiddleware({
        target: 'http://localhost:5000',
        changeOrigin: true,
        pathFilter: '/auth/google',
        
      })
  );
};

Upvotes: 0

samuelmayna
samuelmayna

Reputation: 63

I had the same problem. The problem is not the setupProxy.js, the problem is that the path to which axios is posting does not exist in the backend. This can be caused by a mispelling in the backend route.
Ensure the backend route path is the same as the frontend post path.
First ensure your setupProxy.js looks like this:

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

and the axios.post starts with /api,mine was:

await axios.post("/api/conversion/convert", data);

I was posting using axios.post('/api/conversion/convert') but my express backend had a post route 'api/convertion/convert' which was a typo on my part (convertion instead of conversion) which made axios post to 3000 instead of 5000.
I don't know what kind of a bug is this, axios posting to 3000 instead of 5000 for mismatch in the backend route. The expected behavior is that it should post to 5000/wrong-post-path for easier debugging.

P.S Please upvote if this solves your problem. I am new to answering question and the upvote would really boost my account.

Upvotes: 0

user17121224
user17121224

Reputation: 1

The way to do it is to use what route you use in express at app.get('/what-here', ....) You use also in setupProxy.js at function (app){ app.use('/what-here', createproxyMiddleware({ target: URL, change origin:true}). The what-here is attached to the URL and the URL is proxied to the frontend URL that the client app uses. That is if the client is at localhost:3000 ant the server is at localhost:5000 the request is then at localhost:5000/what-here but it is shown as localhost:3000/what-here to the client. The mistake is to use different names at express then at setupProxy

Upvotes: 0

SHAKU
SHAKU

Reputation: 687

you may need to rewrite your setupProxy.js as below

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

then do a npm install.

In my case that resolved the issue. here you can see more details https://create-react-app.dev/docs/proxying-api-requests-in-development/ Also there it is mentioned as Note: This file only supports Node's JavaScript syntax. Be sure to only use supported language features (i.e. no support for Flow, ES Modules, etc).

Upvotes: 4

Stefan Morcodeanu
Stefan Morcodeanu

Reputation: 2158

i think you forgot to add first part of app.listen(api, proxy()) and you have only proxy method, am problem may be that you didn't specified which url/path to go through proxy.

var express = require('express');
var proxy = require('http-proxy-middleware');

var app = express();

app.use(
  '/api', // you miss this part in your server code
  proxy({ target: 'http://www.example.org', changeOrigin: true })
);
app.listen(3000);

// http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar

Upvotes: -1

Related Questions