【问题标题】:hanging POST requests in Nodejs在 Nodejs 中挂起 POST 请求
【发布时间】:2019-07-05 00:39:53
【问题描述】:

我正在使用 expressjs 来创建和 API。 我还有一个代理服务器可以将请求定向到我的 API 服务器,如下所示:

但在 API 服务器上,POST 和 PUT 请求的正文无法解析,服务器挂起。

// on proxy server
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});

app.all('/api/*', function(req, res){
    proxy.web(req, res, { target: 'http://example.com:9000' });
});
proxy.on('proxyReq', function(proxyReq, req, res, options) {
    if ((req.method == "POST" || req.method == "PUT") && req.body) {
        proxyReq.write(JSON.stringify(req.body));
        proxyReq.end();
    }
});

proxy.on('proxyRes', function(proxyRes, req, res) {
    var body = '';
    proxyRes.on('data', function(chunk) {
        body += chunk;
    });

    proxyRes.on('end', function() {

    });
});

部分api服务器解析body内容。

// on api server
app.use(bodyParser.json({ }));
app.use(bodyParser.urlencoded({ extended: true }));

app.use(cookieParser());
app.use(compress());
app.use(methodOverride());

我意识到它挂在 bodyParser() 中间件中。

任何帮助将不胜感激。我已经在 stackoverflow 上尝试了各种解决方案,但没有一个对我有用。

【问题讨论】:

  • req.body 看起来像什么?真的是 JSON 吗?
  • @shaochuancs bodyparser 无法解析到请求所以没有req.body

标签: node.js express body-parser node-http-proxy


【解决方案1】:

我怀疑您可能忘记将 api 服务器的响应发送回代理服务器。如果是这种情况,那么代理服务器请求将永远挂起等待响应。 在您的 api 路由处理程序中,请确保您正在调用 res.send()method。

我能够在我的机器上运行您的示例,并且在将响应发送回代理服务器后它可以工作。在我的 api 服务器上,这就是我所拥有的:

app.use(bodyParser.json({ }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

app.all('/*',(req,res)=> {
    res.send(req.body);
});
const server = http.createServer(app);
server.listen(9000);

然后,在我的代理服务器上,我添加了用于 cookie 和 json 内容类型信息解析的中间件。

const proxy = httpProxy.createProxyServer({});
const proxyApp = express();
proxyApp.use(bodyParser.json({}));
proxyApp.use(bodyParser.urlencoded({ extended: true }));
proxyApp.use(cookieParser());

proxyApp.all('/api/*', function(req, res){
    proxy.web(req, res, { target: 'http://localhost:9000' });
});

proxy.on('proxyReq', function(proxyReq, req, res, options) {
    if((req.method === 'POST' || req.method === 'PUT') && req.body){
        proxyReq.write(JSON.stringify(req.body));
        proxyReq.end();
    }
});

const proxyServer = http.createServer(proxyApp);
proxyServer.listen(8000);
proxyServer.on('listening',() => {
    console.log('Proxy server listening on port:8000');
});

【讨论】:

    猜你喜欢
    • 2014-01-14
    • 2014-04-30
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 2014-04-04
    • 2018-05-19
    • 2019-09-12
    • 1970-01-01
    相关资源
    最近更新 更多