项目里面需要用到使用NodeJs来转发HTTP POST请求,研究了很久最后才弄通,把过程记录一下:
接收端代码很简单,就是回送body.address属性:
exports.sendEmail = function (req, res) { res.send(200, req.body.address); }
好了,接下来看转发端的代码,为了简单起见,我直接将hard-coding的数据进行转发:
exports.sendEmail = function (req, res) { var data = { address: '[email protected]', subject: "test" }; data = require('querystring').stringify(data); console.log(data); var opt = { method: "POST", host: "localhost", port: 8080, path: "/v1/sendEmail", headers: { "Content-Type": 'application/x-www-form-urlencoded', "Content-Length": data.length } }; var req = http.request(opt, function (serverFeedback) { if (serverFeedback.statusCode == 200) { var body = ""; serverFeedback.on('data', function (data) { body += data; }) .on('end', function () { res.send(200, body); }); } else { res.send(500, "error"); } }); req.write(data + "\n"); req.end(); }
再来看另外一种content type,JSON:
exports.sendEmail = function (req, res) { var data = { address: '[email protected]', subject: "test" }; data = JSON.stringify(data); console.log(data); var opt = { method: "POST", host: "localhost", port: 8080, path: "/v1/sendEmail", headers: { "Content-Type": 'application/json', "Content-Length": data.length } }; var req = http.request(opt, function (serverFeedback) { if (serverFeedback.statusCode == 200) { var body = ""; serverFeedback.on('data', function (data) { body += data; }) .on('end', function () { res.send(200, body); }); } else { res.send(500, "error"); } }); req.write(data + "\n"); req.end(); }
另外,有两个地方,我不是很清楚,一个是貌似content-length不是必须的,另一个是req.write(data+"\n")的"\n"也不是必须的,这个有待研究。。。
补充:
bodyparser的代码在”\node_modules\express\node_modules\connect\lib\middleware\bodyParser.js“,它其实什么都没做,只是把解析body的任务派发给了另外3个中间件:./multipart, ./urlencoded, ./json: