21

I use create-react-app to bootstrap my react app, I did this in my package.json

"proxy":"http://localhost:3001" because my api server is running on 3001, but I fire request using axios, it still point to port 3000, any clue what is missing? restarted my app several times it still the same.

Jenny Mok
  • 2,744
  • 9
  • 27
  • 58
  • 2
    I got the same issue. Finally, I found that I sent the wrong body (for instance, it should be: body: JSON.stringify(authData) rather than: body: JSON.stringify({authData}). But the main point here is the console still logged my client-side port (3000) rather than the server-side one (3001) after I got the correct result: "Fetch finished loading: POST "http://localhost:3000/api/auth/signin"." So, it seems to me that I couldn't depend on the console to know whether proxy worked or not. In my case, adding "proxy":"http://localhost:3001" is enough. My bug was on the request itself. – Nguyen Jan 19 '18 at 20:29

12 Answers12

13

In your package.json add:

"proxy": "http://localhost:3001",

Please restart both your server ( backend app ) and front-end ( Create React App )

Make sure that your post request with axios it's like below:

axios.post("/auth/register", userData)
     .then(res => console.log(res.data));

This example above it's from my environment and works as well. Notice that proxy works only for development mode

Ensure your code that has the right slash in url in proxy and in axios post both

xargr
  • 2,788
  • 1
  • 19
  • 28
  • Great , I'v viewed several solution and this is the only one worked for me. for the other readers out there make sure like he mentioned to turn off/ restart the client and the backend side as this was my problem. – Moody Omar Oct 22 '21 at 14:28
3

Try to remove absolute path for request, and use relative path instead.

Example

axios.post("/api/auth/register", userData)
 .then(res => console.log(res.data));

Note: Do not use http://localhost:3000/api/auth/register as the request URI, it (React server) will automatically proxying the request, and the API request will serve from 3001 port.

Malay M
  • 1,659
  • 1
  • 14
  • 22
3

I had this problem and I did everything "correct". For me GET requests were going to my proxy but not POST! I got Request Aborted error.

Discovered solution by accident that my data : { key: value} needed to be properly quoted as data : { "key": value }.

Riaan Schutte
  • 535
  • 1
  • 5
  • 14
2

Issue is in webpack config file,with your own starter pack just set webpack.dev.js as in code bellow

module.exports = merge(common, {
  mode: 'development',
  devServer: {
    host: 'localhost',
    port: 3000,
    open: true,
    historyApiFallback: true,
    proxy: {
      '/api': {
        target: 'http://localhost:5000',
        secure: false
      }
    }
  },
  devtool: 'inline-source-maps'
}); 

and set appropriate localhost for your server and restart dev-server. In "create-react-app" webpack config files should be on path /node_modules/react-scripts/config , make changes as in code above and restart dev-server and you should be fine. On this path are webpack.dev.js and webpack.prod.js.

Mahesh Kumaran
  • 887
  • 2
  • 12
  • 30
Goran_Ilic_Ilke
  • 812
  • 12
  • 16
0

Replace your proxy config with this: "proxy": "http://127.0.0.1:5000", Make sure your proxy is added in client side of package.json and do a hard restart using ctrl+c after moving proxy config to client side.

0

I know this post is old but I recently had the same issue.

What fixed it for me was using the npm package axios to make API requests instead of the native JavaScript fetch API.

I didn't look deep enough to see what request headers axios was doing differently than fetch, but everything works fine for me now.

podenborg
  • 78
  • 5
0

I started with create-react-app, then added Node.js Express server (on Mac OS). After reading many solutions, restarting the server many times, I was still struggling to make it work with the proxy and be able to fetch('/api/hello'). Here is what actually works for me:

Changing webpack.config.js

devServer: {
    open: true,
    historyApiFallback: true,
    proxy: {
            '/api': {
                    target: 'http://localhost:3001',
                    secure: false
            }
    }
},

I restarted my computer (it apparently worked for some people). I discovered later that devServer was defined twice in webpack.config.js...

gaelle
  • 1
  • 3
0

I read the answer that problem can cause using fetch instead of axios. Is not true, fault is incorrect request/body (you need look in your code).

For all who is looking for answers pleas be aware that is different solution if you create app by creat-react-app and don't have a webpack.config.js. Then enough what you need to set up is adding proxy to your package.json

How should look proper fetch request:

 const options =  {
  method: 'POST', // *GET, POST, PUT, DELETE, etc.
  mode: 'cors', // no-cors, cors, *same-origin
  cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
  credentials: 'include', // include, *same-origin, omit, chosen include to allowed sending cookies
  headers: {
    'Content-Type': 'application/json',
    COOKIE: 'key=value; Path=/; Expires=Thu, 09 Jul 2020 07:20:21 GMT; HttpOnly',
  },
  body: JSON.stringify({ something }), // body data type must match "Content-Type" header in this case it is json
})

 fetch(url, options)
    .then(res => {
      //return res.json!
        return res.json(); 
    })
    .then(data => {
        // do something with data
    })

For better debugging is good add a printscreen of network tab from dev tools

adabedi
  • 36
  • 2
0

Proxy settings for the development environment:

package.json contains:

...
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:3001"
...
...
  axios({
        method: "post",
        proxy: {
            host: "localhost",
            port: 3001
        },
        .
        .
        .
    })
...

Proxy settings for the production environment:

create a serve.json file in the public folder and insert any of these properties:

serve.json contains:

 {
  "redirects": [
    { "source": "/api", "destination": "http://localhost:3001/" }
  ]
 }
npm install -g serve
serve -s build
0

From create-react-app.dev/docs see:

The development server will only attempt to send requests without text/html in its Accept header to the proxy.

So any request with that header, for example a GET request sent in response to a click on a link (anchor tag ) will not be proxied. I suggest starting by looking as the "Accept" field of the request header in the browser dev tools.

Mike Thielvoldt
  • 181
  • 1
  • 11
  • 1
    Or if you need to proxy a request that returns text/html (e.g. authentication flows or other redirects) see this similar question: https://stackoverflow.com/questions/62236347/is-it-possible-to-proxy-the-html-get-request-to-graphql-from-a-create-react-app – Alexander Taylor Mar 04 '22 at 00:12
-1
  1. it is just a windows permission issue, even it works on mac frequently.
  2. I just install - yarn global add http-server on server side, now it is working fine from the client side
sanjeev
  • 1
  • 1
-4

Try this:

{
  "proxy": {
    "/api/foo": {
      "target": "your url" ,
      "changeOrigin": true
     },
    "/api/bar": {
      "target": "another url",
      "changeOrigin": true
     },
   }
}
sammy
  • 437
  • 4
  • 11