问题
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
Can someone point out what i have to do to fix this issue so that the request actually goes to port 5000?
回答1:
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:
Make sure you put it on package.json in client side (react) instead of on package.json in server-side(node).
来源:https://stackoverflow.com/questions/48291950/proxy-not-working-for-react-and-node