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?
28 Answers 28
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.
- Stop your React app
- Delete package-lock.json file and the node_modules directory by doing
rm -r package-lock.json node_modules
in the app directory. - Then do
npm installin the app directory.
Hopefully this fixed your proxy issue.
5 Comments
The reason the react application is still pointing at localhost:8080 is because of cache. To clear it , follow the steps below.
- Delete
package-lock.jsonandnode_modulesin React app- Turn off React Terminal and
npm installall dependencies again on React App- 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.
1 Comment
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()],
});
1 Comment
This is how I achieved the proxy calls.
- 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 -
Server logs -
- Check if your server is really running on the same path
/api/hellothrough postman or browser. For me it was/api/user/registerand I was trying to hit/api/user - Use cors package to disable cross-origin access issues.
1 Comment
/ . 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/helloFor 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.
1 Comment
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.
2 Comments
proxy setting from package.json. It uses your webpack config for any proxy setting, as seen in the documentation here Make sure you put it on package.json in client side (react) instead of on package.json in server-side(node).
Comments
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
2 Comments
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!- you should set the proxy address to your backend server, not react client address.
- you should restart the client after changing
package.json - you should use
fetch('/api/...')(instead offetch('http://localhost:8080/api/'))
Comments
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,
- killed all the terminals so that I can stop frontend and backend servers both.
- 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())
- 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.
Comments
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.
1 Comment
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.
Comments
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.
Comments
Your backend data or files and react build files should be inside the same server folder.
3 Comments
you must give proxy after the name.{"name":"Project Name", "proxy":"http://localhost:5000"}
port should match with your backend's port.
Comments
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://stackoverflow.com/a/51051360/345648
(This doesn't answer the original question, but searching Google for that question took me here so maybe this will help others like me.)
Comments
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.
Comments
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}` }
));`
1 Comment
For me, I solved this by just stopping both the servers i.e. frontend and backend, and restarting them back again.
Comments
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:"",
}
)
1 Comment
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:
Comments
faced similar issue. my proxy was not connecting restarting the react app fixed my issue
Comments
In my case it was because of typo. I wrote "Content-type": "application/json", (with small t) instead of "Content-Type": "application/json",
Comments
Comments
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.
Comments
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/, ''),
},
},
},
});
Comments
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: 2024年3月25日 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,
Comments
Make sure your end point match with the backend.
Comments
Explore related questions
See similar questions with these tags.