1
votes

"proxy": "http://localhost:3001" in my package.json where the express server is running on this port ( 3001 ), but every time I am hitting a request from react it's going on 3000 port on which react app is running

package.json

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "antd": "^3.10.2",
    "axios": "^0.18.0",
    "dotenv": "^6.1.0",
    "http-proxy-middleware": "^0.19.0",
    "material-ui": "^0.20.2",
    "react": "^16.5.2",
    "react-bootstrap": "^0.32.4",
    "react-dom": "^16.5.2",
    "react-form": "^3.5.6",
    "react-redux": "^5.0.4",
    "react-router-dom": "^4.3.1",
    "react-router-redux": "^5.0.0-alpha.5",
    "react-scripts": "2.0.5",
    "styled-components": "^4.0.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

setupProxy.js

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

module.exports = function(app) {
  app.use(proxy('/api/*', { target: 'http://localhost:3001' }));
};
3
in your index.js define const PORT = process.env.PORT || 3001; - User123456

3 Answers

0
votes
"proxy": {
"/services": {
  "target": "http://localhost:3001",
  "changeOrigin": true,
  "pathRewrite": {
    "^/services": ""
  }
}

}

npm start again

0
votes

You can define the port in your index.js

const PORT = 3001;

and use

"proxy": { "/*": { "target": "http://localhost:3001" } }

in client package.json

for http-proxy-middleware: install the package. create a file called setupProxy.js and inside it use below pattern

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

module.exports = function(app) {
  app.use(proxy('/', { target: 'http://localhost:3001' }));
};

Remember to remove the old proxy scripts code from your client side package.json .

0
votes

If you are using new version http-proxy-middleware ("1.X.X"), the code could be changed to the following:

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

module.exports = function(app) {
  app.use('/console/api', createProxyMiddleware({ 
    target: 'http://localhost:8080/', 
    changeOrigin: true, 
    pathRewrite: {'^/console/api' : ''} 
  }));
};

In other words, proxy should be replaced with createProxyMiddleware