NodeJS 我在使用http-proxy-middleware时遇到问题

uttx8gqw  于 2023-01-30  发布在  Node.js
关注(0)|答案(3)|浏览(272)

我有两个服务器运行在我的后端,因为我必须使用http代理中间件包,但我遇到了一些问题。
这是我在本地主机3000上运行的前端代码

axios("/api2/login",data)
    .then((res) => {
});

这是我在本地主机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)

我不明白我错在哪里。

qxgroojn

qxgroojn1#

看起来它击中了localhost:3000,而不是localhost:5001,这是你的服务器运行的地方。

axios("http://localhost:5001/api2/login",data)
    .then((res) => {
});

您还可以在axios. HTTP get request with Axios gets sent with the local host IP at the beginning of the URL中设置baseURL

nhaq1z21

nhaq1z212#

如果我没理解错的话,您的服务器正在侦听端口5001,因此,您需要将请求从3000代理到5001,您可以在react应用程序中通过设置package.json中的代理值来完成此操作:

"proxy": "http://localhost:5001",

有关此主题的详细信息,请查看the docs

编辑注解部分中说明的配置

包中的第一个。json:

"proxy": "http://localhost:5002",

创建将在端口5002上侦听的新服务器(proxyserver):

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);
jbose2ul

jbose2ul3#

我遵循了这个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

相关问题