proxy not working for react and node
Asked Answered
D

28

67

I'm having issues with the proxy I set up.

This is my root package.json file:

"scripts": {
    "client": "cd client && yarn dev-server",
    "server": "nodemon server.js",
    "dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
}

My client package.json file:

"scripts": {
    "serve": "live-server public/",
    "build": "webpack",
    "dev-server": "webpack-dev-server"
},
"proxy": "http://localhost:5000/"

I've set up express on my server side to run on port 5000. Whenever I make a request to the server, ie :

callApi = async () => {
    const response = await fetch('/api/hello');
    const body = await response.json();
    // ... more stuff
}

The request always goes to

Picture of header pointing to http://localhost:8080/api/hello

Can someone point out what i have to do to fix this issue so that the request actually goes to port 5000?

Dyaus answered 17/1, 2018 at 0:31 Comment(0)
H
77

I experienced this issue quite a few times, and I figured it's because of the cache. To solve the issue, do the following


Edit: @mkoe said that he was able to solve this issue simply by deleting the package-lock.json file, and restarting the app, so give that a try first. If that doesn't resolve it, then do the following.


  1. Stop your React app
  2. Delete package-lock.json file and the node_modules directory by doing
    rm -r package-lock.json node_modules
    in the app directory.
  3. Then do npm install in the app directory.

Hopefully this fixed your proxy issue.

Humblebee answered 1/9, 2020 at 14:51 Comment(7)
Actually just deleting package-lock.json and restarting worked for me, so you may want to try this first before reinstalling node_modules.Durwood
You've nailed it! If you're using create-react-app this should be the accept answer. Thank youAmarette
After stopping the React app the following worked for me. 1. delete package-lock.json 2. npm i --package-lock-only # recreates package-lockTenpin
I deleted package-lock.json and restarted npm start and package-lock.json was never recreated. I did npm i --package-lock-only and it recreated the package-lock but package-lock still doesn't show any reference to proxy as I have in package.jsonMegasporangium
Thank you Very Much, this solved the issueAlie
This did not work for me. Week 3 still have the same problem.Lota
bro thank you so much, i thought i was going crazyLough
D
18

The reason the react application is still pointing at localhost:8080 is because of cache. To clear it , follow the steps below.

  1. Delete package-lock.json and node_modules in React app
  2. Turn off React Terminal and npm install all dependencies again on React App
  3. Turn back on React App and the proxy should now be working

This problem has been haunting me for a long time; but if you follow the steps above it should get your React application pointing at the server correctly.

Disafforest answered 23/4, 2020 at 4:56 Comment(1)
well that wasted several minutes of my time not realizing that it was cached. Should have realized. Have had similar issues on web servers before, but I forgotFrau
S
15

This is how I achieved the proxy calls.

  1. Do not rely on the browser's network tab. Put consoles in your server controllers to really check whether the call is being made or not. For me I was able to see logs at the server-side. My node server is running on 5000 and client is running on 3000.

Network tab -

Dev tools network tab

Server logs -

server

  1. Check if your server is really running on the same path /api/hello through postman or browser. For me it was /api/user/register and I was trying to hit /api/user
  2. Use cors package to disable cross-origin access issues.
Suisse answered 23/5, 2020 at 11:57 Comment(1)
Make sure you check the url. It should start with a / . If you're on a page localhost/user, then without the first slash fetch('api/hello') will resolve to localhost/user/api/hello, where it was meant to go to localhost/api/helloReadymade
W
15

I was having this issue for hours, and I'm sure some of the things above could be the cause in some other cases. However, in my case, I am using Vite and I had been trying to add my proxy to the package.json file, whereas it should be added to the vite.config.js file. You can click here to read about it in Vite's docs.

In the end, my code looks like this:

export default defineConfig({
  server: {
    proxy: {
      "/api": {
        target: "http://localhost:8000",
        secure: false,
      },
    },
  },
  plugins: [react()],
});
Windward answered 4/12, 2022 at 20:9 Comment(1)
+1. For react-admin, I've used the /api config as is from vitejs.dev/config/server-options.html#server-proxy and set VITE_SIMPLE_REST_URL=localhost:5173/api in the .env file.Gloriole
P
8

For me "proxy" = "http://localhost:5000 did not work because I was listening on 0.0.0.0 changing it to "proxy" = "http://0.0.0.0:5000 did work.

Photojournalism answered 6/10, 2020 at 4:30 Comment(1)
After trying multiple solutions, finally this is worked.Wolpert
M
6

Is your client being loaded from http://localhost:8080?

By default the fetch api, when used without an absolute URL, will mirror the host of the client page (that is, the hostname and port). So calling fetch('/api/hello'); from a page running at http://localhost:8080 will cause the fetch api to infer that you want the request to be made to the absolute url of http://localhost:8080/api/hello.

You will need to specify an absolute URL if you want to change the port like that. In your case that would be fetch('http://localhost:5000/api/hello');, although you probably want to dynamically build it since eventually you won't be running on localhost for production.

Marquez answered 17/1, 2018 at 0:44 Comment(2)
I get that, but shouldn't the proxy take care of that? What's the purpose in having it there if it isnt?Dyaus
What exactly are you thinking will make use of the "proxy" value you have set there? Your scripts lead me to believe that you're using webpack-dev-server for developement, but it won't pick up a proxy setting from package.json. It uses your webpack config for any proxy setting, as seen in the documentation hereMarquez
M
6

Make sure you put it on package.json in client side (react) instead of on package.json in server-side(node).

Maharanee answered 20/6, 2019 at 5:33 Comment(0)
S
4

This solution worked for me, specially if you're using webpack.

Go to your webpack.config.js > devServer > add the below

proxy: {       '/api': 'http://localhost:3000/', },

This should work out.

Read more about webpack devSever proxy: https://webpack.js.org/configuration/dev-server/#devserver-proxy

Ssw answered 5/2, 2021 at 18:43 Comment(2)
You are a god. If you are using webpack-dev-server for your development environment, adding the proxy in the webpack.config.js file as described in the linked documentation will solve it! Thanks!Manque
Wow. This helped me out as well. I am running my react client with webpack-dev-server on localhost:3000 I set proxy in dev-server to point to node.js server which is running on localhost:3001 and it just worked! Thank you so much.Weird
H
2
  1. you should set the proxy address to your backend server, not react client address.
  2. you should restart the client after changing package.json
  3. you should use fetch('/api/...') (instead of fetch('http://localhost:8080/api/'))
Hans answered 21/10, 2020 at 21:57 Comment(0)
M
2

I have tried to solve this problem by using so many solutions but nothing worked for me. After a lot of research, I have found this solution which is given below that solved my proxy issues and helped me to connect my frontend with my node server. Those steps are,

  1. killed all the terminals so that I can stop frontend and backend servers both.
  2. Installed Cors on My Node server.js file.
npm install cors

And added these lines into server.js file

var cors = require('cors')

app.use(cors())

  1. Into package.json file of frontend or client folder, I added this line,
"proxy" : "http://127.0.0.1:my_servers_port_address_"

Now everything working fine.

Millford answered 28/8, 2021 at 17:46 Comment(0)
O
1

Yours might not be the case but I was having a problem because my server was running on localhost 5500 while I proxied it to 5000.

I changed my package.json file to change that to 5500 and used this script:

npm config set proxy http://proxy.company.com:8080 npm config set https-proxy http://proxy.company.com:8080

I am pretty sure just changing it on the package.json worked but I just wanted to let you know what I did.

Ordway answered 22/7, 2020 at 22:53 Comment(1)
yeah, just change it on the package.json file. Using that script messed up by proxy I think.Ordway
L
1

Make sure you check your .env variables too if you use them. It's because of that if I was looking for a solution on that page.

Legge answered 18/11, 2020 at 2:59 Comment(0)
T
1

I tried all the solutions, proposed here, but it didn't work. Then I found out, that I tried to fetch from root directory (i.e. fetch('/')) and it's not correct for some reason. Using fetch('/something') helped me.

Tolerant answered 10/5, 2021 at 7:28 Comment(0)
V
1

Your backend data or files and react build files should be inside the same server folder.

Vouge answered 19/6, 2021 at 6:29 Comment(3)
it's an opinion not answer. can you be specific?Conlon
its a way to communicat with your backend api otherwise when you deploye your application on server then you will face 404 not found error if you used proxy for base uri of backend.Vouge
yeah, be specific that way you responded to me with more details in your answer.Conlon
C
1

you must give proxy after the name.{"name":"Project Name", "proxy":"http://localhost:5000"} port should match with your backend's port.

Churchgoer answered 24/6, 2021 at 8:37 Comment(0)
N
1

If you are seeing your static react app HTML page being served rather than 404 for paths you want to proxy, see this related question and answer:

https://mcmap.net/q/296942/-proxy-in-package-json-not-affecting-fetch-request

(This doesn't answer the original question, but searching Google for that question took me here so maybe this will help others like me.)

Neves answered 3/3, 2022 at 23:23 Comment(0)
B
1

In my specific case, I had a both Node backend, and an inner folder with a React project. I tried @Harshit's answer, which didn't work, until I had two package.json files in my project, one in the outer folder, and one in my client (React) folder. I needed to set up the proxy in the inner package.json, and I needed to clear the cache in the inner folder.

Bicollateral answered 12/6, 2022 at 15:54 Comment(0)
D
0

My problem was actually the "localhost" part in the proxy route. My computer does not recognize "localhost", so I swapped it with http://127.0.0.1:<PORT_HERE> instead of http://localhost:<PORT_HERE>.

Something like this:

app.use('/', proxy(
    'http://localhost:3000', // replace this with 'http://127.0.0.1:3000'
    { proxyReqPathResolver: (req) => `http://localhost:3000${req.url}` }
));`
Dunagan answered 23/1, 2022 at 15:3 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Mada
R
0

For me, I solved this by just stopping both the servers i.e. frontend and backend, and restarting them back again.

Raff answered 8/7, 2022 at 20:5 Comment(0)
S
0

Here is an opinion Don't use proxies, use fetch directly

not working

fetch("/signup", {    
        method:"post", 
        headers:{
            "Content-Type":"application/json" 
        },
        body:JSON.stringify(
        {
            name:"",
            email:"",
            password:"",
        }
        )

Actually worked after wasting 6hours

fetch("http://localhost:5000/signup", {    //    https -> http
        // fetch("/signup", {    
        method:"post", 
        headers:{
            "Content-Type":"application/json"              },
        body:JSON.stringify(
        {
            name:"",
            email:"",
            password:"",
        }
        )
Sharrisharron answered 19/7, 2022 at 8:17 Comment(1)
This will result in CORS errorDonatello
M
0

In my case the problem was that the proxy suddenly stopped to work.

after investigating I found that I've moved the setupProxy from the src folder and that cause the problem.

Moving it back to the src folder have solved the problem.

The problematic structure: enter image description here

The solution:

enter image description here

Mohave answered 23/10, 2022 at 11:43 Comment(0)
A
0

faced similar issue. my proxy was not connecting restarting the react app fixed my issue

Athamas answered 26/10, 2022 at 4:40 Comment(0)
Z
0

In my case it was because of typo. I wrote "Content-type": "application/json", (with small t) instead of "Content-Type": "application/json",

Zarathustra answered 23/11, 2022 at 12:24 Comment(0)
A
0

you should install this package:

npm install http-proxy-middleware --save

refrense: this link

Altdorf answered 15/12, 2022 at 20:17 Comment(0)
E
0

TLDR answer in 2023: the problem is that modern versions of Node starting with v17.0.0 default to IPv6 instead of IPv4 domain resolution, and you may be operating in an environment that doesn't support, restricts, or is misconfigured for IPv6 (most likely corporate or school).

Longer answer: If none of the answers in this thread are working for you in 2023 (there were 25 at the time I'm writing this, and none addressed WHY this is happening), and you are positive that your app is configured correctly, the problem is most likely due to Node defaulting to IPv6 instead of IPv4 when it's performing DNS resolution. This IPv6 default started in version 17.0.0 of Node -- you can read more about it here.

If you are working in a network environment that restricts or hasn't migrated to IPv6 support yet, this will break your app -- localhost will resolve to ::1 (the IPv6 equivalent of 127.0.0.1), and you'll get a connection refused error, like everyone is complaining about here. Try to visit http://[::1]:5000 in Chrome or whatever browser, and you will get the same error. But if http://127.0.0.1:5000 works, this is 100% your problem.

The fix is super easy. Just force Node to resolve with IPv4. There's many ways to do this depending on your setup, but you'll have to abandon the proxy setting in package.json, and rely on Node's own native dns module. Given that this question is about a create-react-app app, and my problem occurred in one too, I'll give an example of how I fixed it here. But you can do this with pretty much any Express server.

As mentioned, get rid of the proxy setting in package.json, and instead create a setupProxy.js file in your /src directory (like explained here). You'll also need to install the http-proxy-middleware module via npm. Then, you'll basically want to do your own IPv4-forced DNS lookup and create a proxy request using that IPv4 address. You can do this with the family parameter set to 4 in the dns.lookup method, as shown here:

const dns = require("dns");
const { createProxyMiddleWare } = require("http-proxy-middleware");

const targetHost = "localhost";
const targetPort = 5000;
const port = 3000;

module.exports = function (app) {
    dns.lookup(targetHost, { family: 4 }, (err, address) => {
        if (err) {
            console.error('DNS lookup failed');
            return;
        }
        const proxy = createProxyMiddleware("/api", {
            target: `http://${address}:${targetPort}`,
            changeOrigin: true,
        });
        app.use("/api", proxy);
    });
};

Now if you hit http://localhost:3000/api/yourendpoint, this will redirect to http://127.0.0.1:5000 instead of http://[::1]:5000. Note that this is a very basic example and leaves out error handling and ignores the fact that dns lookup is an asynchronous operation, but overall this should work if you're in an environment where IPv6 doesn't work properly.

Estes answered 15/12, 2023 at 3:3 Comment(0)
P
0

This issue can occur with Vite or Cors.

Step 1: Setup CORS. (Cross-Origin Resource Sharing): restricts web pages from making requests to a different domain than the one that served the web page.In the context of Node.js applications, if your frontend (e.g., a React app) is hosted on a different domain or port than your backend API, you will likely encounter CORS restrictions. When a browser detects that a web page is trying to make a cross-origin request, it sends an HTTP request with an Origin header indicating the origin of the requesting site. The server then needs to decide whether to allow or deny the request based on this information.

Install the cors Package on the server:

npm install cors

import on the index.js

const cors = require('cors');

// Enable CORS for all routes
app.use(cors());

Still Not Working ? Vite configuration might be a solution.

Step 2: In Vite, which is a build tool for modern web development, there isn't a built-in proxy option in the package.json file like you would find in Create React App. Instead, Vite uses a server setup for handling both development and production environments.

To configure proxying in Vite, you would typically use the vite.config.js file to define a custom server with proxy settings. Here is an example of how you can set up proxying in Vite:

// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': { 
        //in your case [/api] can be different
        target: 'http://localhost:3000', // Replace with your backend server URL
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
});
Publicness answered 28/1 at 7:20 Comment(0)
C
0

No need to remove node_modules or anything else. Just add the proxy entry in your package.json (as you did)

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

just try to fetch the backend using json format.

i.e. django-react-app http http://localhost:3000/prompts/ HTTP/1.1 200 OK Access-Control-Allow-Headers: * Access-Control-Allow-Methods: * Access-Control-Allow-Origin: * Content-Encoding: gzip Transfer-Encoding: chunked Vary: Accept, origin, Cookie, Accept-Encoding X-Powered-By: Express allow: GET, POST, HEAD, OPTIONS connection: keep-alive content-type: application/json cross-origin-opener-policy: same-origin date: Mon, 25 Mar 2024 11:07:38 GMT referrer-policy: same-origin server: WSGIServer/0.2 CPython/3.11.8 x-content-type-options: nosniff x-frame-options: DENY

{ "count": 1,

Chromatid answered 25/3 at 11:13 Comment(0)
R
-5

Make sure your end point match with the backend.

Rodrich answered 5/12, 2020 at 17:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.