API 尽管添加了代理,调用仍未重定向到所需的目标

API calls not not redirected to the required target despite adding a proxy

尽管添加了代理,API 调用没有重定向到所需的目标 url。

我使用 create-react-app 创建了一个聊天机器人应用程序。我想将所有从 http://localhost:3000/ 发出的 API 调用重定向到 http://localhost:5000/ 并完成此操作,我已按照 https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development#configuring-the-proxy-manually

中的说明配置了代理

编译代码时,似乎已添加代理,但在 运行 浏览器中的应用程序上, api 调用尚未重定向到 http://localhost:5000

代理设置代码:

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
    app.use(proxy('/api/*', { target: 'http://localhost:5000/' }));
}

API 调用:

const chatbot = require('../reactbot-backend/chatbot')

module.exports = app => {

app.get('/', async (req, res) => {
    res.send({'hello': 'johnny'});

});

app.post('/api/df_text_query', async (req, res) => {
    let responses = await chatbot.textQuery(req.body.text, req.body.parameters);
    res.send(responses[0].queryResult);
});

app.post('/api/df_event_query', async (req, res) => {
    let responses = await chatbot.eventQuery(req.body.event, req.body.parameters);
    res.send(responses[0].queryResult);
});
};

在编译代码时,我得到以下信息:

[0] [HPM] Proxy created: /api/*  ->  http://localhost:5000/
[0] Starting the development server...
[0]
[0] Compiled successfully!

这是在 API 调用中获得的错误:

http://localhost:3000/api/df_event_query:1 Failed to load resource: net::ERR_EMPTY_RESPONSE

createError.js:17 Uncaught (in promise) Error: Network Error
    at createError (createError.js:17)
    at XMLHttpRequest.handleError (xhr.js:87)

http://localhost:3000/api/df_event_query 表示 api 呼叫未被重定向

添加 changeOrigin:true 解决了这个问题

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
    app.use(proxy('/api/*', { target: 'http://localhost:5000/' , changeOrigin: true}));
}