gpt4 book ai didi

node.js - 调用 bodyParser.json() 后如何使用 "express-http-proxy"?

转载 作者:搜寻专家 更新时间:2023-10-31 23:42:36 25 4
gpt4 key购买 nike

我正在构建一个跨系统管理应用程序,它将用作多个后端系统的管理工具。该应用程序构建在 Mean.js 之上。

我已经使用“express-http-proxy”设置了一个/proxy 路由,以将所有子路由发送到它们各自的后端系统端点。但是,我需要在我的管理应用程序中对每个请求进行身份验证,然后在“express-http-proxy”可以继续之前使用目标后端系统凭据进行装饰。这是我的 /proxy 路由的示例...

app.use('/proxy', users.requiresLogin, expressHttpProxy(config.backendSystem.host, {
forwardPath: function (req) {
return '/1.0' + require('url').parse(req.url).path;
},
decorateRequest: function (req) {
req.headers['content-type'] = 'application/json';
req.headers['backend-system-id'] = config.backendSystem.id;
req.headers['backend-system-key'] = config.backendSystem.key;
return req;
}
}));

注意:
目前后端系统凭据是根据我的管理应用程序运行的环境存储的。但是,将来后端系统凭据将由用户指定,并且此 /proxy 路由将有所不同比当前显示的要多。

问题:
请求主体中需要数据的代理路由不起作用。
例如POST/comments {"user": user_id, "text": "rabble rabble rabble"}

我发现了什么:
bodyParser.json() 和“express-https-proxy”表现不佳。我已通过从 express.js 中删除 bodyParser.json() 来确认这一点。然而,这不是一个完整的解决方案,因为我几乎所有其他路线都需要 bodyParser.json,例如/auth/signin.

有没有人有一个干净的方法可以为我的 /proxy 路由设置一个路由异常,这样 bodyParser.json 就不会被调用?

最佳答案

据我了解,问题的根源是这样的:

如果你正在通过纯 Node 读取 POST 请求,你应该使用这样的代码

if (req.method == 'POST') {
console.log("POST");
var body = '';
req.on('data', function (data) {
body += data;
console.log("Partial body: " + body);
});
req.on('end', function () {
console.log("Body: " + body);
});
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('post received');
}

换句话说,您需要使用 req.on('data') 和 req.on('end') 事件。但问题是,您只能使用此代码一次。调用'end'后,请求被消费。

然后你使用 bodyParser ,它消耗请求,代理与它无关。

实际上,在我看来,代理等待“数据”事件出现,但它会更新发生,所以代码停止。

解决方法:

您需要“重新启用”事件。我使用了这段代码,它对我有用。

var express = require('express');
var bodyParser = require('body-parser');
var http = require('http');

//call for proxy package
var devRest = require('dev-rest-proxy');

//init express (as default)
var users = require('./routes/users');
var app = express();
app.use(bodyParser.json());

//set the proxy listening port
app.set('port', 8080);

//process the POST request
app.post('/users/*', function(req, res) {

//just print the body. do some logic with it
console.log("req.body: ",req.body);

//remove listeners set by bodyParser
req.removeAllListeners('data');
req.removeAllListeners('end');

//add new listeners for the proxy to use
process.nextTick(function () {
if(req.body) {
req.emit('data', JSON.stringify(req.body));
}
req.emit('end');
});

//forward the request to another server
devRest.proxy(req,res, 'localhost', 3000);

});

//start the proxy server
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});

module.exports = app;

schumacher-m 上找到的解决方案post(nodejitsu的github)

关于node.js - 调用 bodyParser.json() 后如何使用 "express-http-proxy"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28371641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com