问题描述
我设置的代理存在问题.
I'm having issues with the proxy I set up.
这是我的根package.json文件:
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\""
}
我的客户端package.json文件:
My client package.json file:
"scripts": {
"serve": "live-server public/",
"build": "webpack",
"dev-server": "webpack-dev-server"
},
"proxy": "http://localhost:5000/"
我已经在服务器端设置了express以在端口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
}
请求始终发送到
有人可以指出要解决此问题以便将请求实际发送到端口5000的情况吗?
Can someone point out what i have to do to fix this issue so that the request actually goes to port 5000?
推荐答案
是否正在从http://localhost:8080
加载您的客户端?
Is your client being loaded from http://localhost:8080
?
默认情况下,在不使用绝对URL的情况下使用fetch
api时,它将镜像客户端页面的主机(即主机名和端口).因此,从运行在http://localhost:8080
的页面调用fetch('/api/hello');
将导致fetch
api推断您希望将请求发送到http://localhost:8080/api/hello
的绝对URL.
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
.
如果要这样更改端口,则需要指定一个绝对URL.在您的情况下为fetch('http://localhost:5000/api/hello');
,尽管您可能希望动态构建它,因为最终您将不会在localhost
上运行以进行生产.
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.
这篇关于代理不适用于反应和节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!