如何解决我在使用 http-proxy-middleware 编辑评论部分中解释的配置
我的后端有两台服务器在运行,因此我必须使用 http-proxy-middleware 包,但我遇到了一些问题。
这是我在 localhost:3000 上运行的前端代码
axios("/api2/login",data)
.then((res) => {
});
这是我在 localhost:5001 上运行的后端代码
const { createProxyMiddleware } = require('http-proxy-middleware');
app.use(createProxyMiddleware('/api2',{target: 'http://localhost:5001',changeOrigin: true}))
app.post("/login",(req,res,next) => {
res.send("Logged In");
});
GET http://localhost:3000/api2/login 404 (Not Found)
Uncaught (in promise) Error: Request Failed with status code 404
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)
我无法理解我哪里出错了。
解决方法
看起来它正在点击 localhost:3000
而不是 localhost:5001
,这是您的服务器运行的地方。
axios("http://localhost:5001/api2/login",data)
.then((res) => {
});
你也可以在 axios 中设置 baseURL。 HTTP get request with Axios gets sent with the local host IP at the beginning of the URL
,如果我理解正确,您的服务器正在侦听端口 5001。因此,您需要将您的请求从 3000 代理到 5001。您可以通过在 package.json 中设置代理值在 react 应用程序中执行此操作:
"proxy": "http://localhost:5001",
有关此主题的更多信息,请查看 the docs。
编辑评论部分中解释的配置
在 package.json 中的第一个:
"proxy": "http://localhost:5002",
创建一个新的服务器 (proxyserver),它将在端口 5002 中侦听:
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
// redirection for first server 5000
app.use('/api1',createProxyMiddleware({ target: 'http://localhost:5000',changeOrigin: true }));
// redirection for second server 5001
app.use('/api2',createProxyMiddleware({ target: 'http://localhost:5001',changeOrigin: true }));
app.listen(5002);
对于其他服务器(5000 和 5001),您不需要重定向请求。只需确保他们正在侦听正确的端口(5000 和 5001),例如:
const express = require('express');
const app = express();
app.post("/api2/login",(req,res,next) => {
res.send("Logged In");
});
app.listen(5001);
,
我按照此 post 中提到的步骤进行了一些更改,
我将我的 Axios 请求代码更改为:
axios({
method: "POST",data: user,withCredentials: true,url: "/api2/login",}).then((res) => {})
否则,代理服务器会将其视为 GET 请求。
其次,我将代理服务器中的代理端点代码更改为:
app.use('/api2',createProxyMiddleware({
target: 'http://localhost:5001',changeOrigin: true,pathRewrite: {
[`^/api2`]: '',},}));
有关代理端点更改的更多信息,请参见 here。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。