我有一个web应用程序从传感器收集数据。传感器通过POST请求将数据发送到我的webapp example.com
。Node.js请求模块不能POST POST到外部URL
为了调试目的,我需要在传感器和webapp之间创建一个额外的层。
我已经创建了一个额外的小web应用程序,所有这确实是采取传入POST请求example.com
并将其转发给web应用程序,现在应对不同的URL,说example2.com
。
所以,这是以前:
sensors -> example.com (webapp)
现在是:
sensors -> example.com -> example2.com (webapp)
这样我能看到什么是web应用程序的响应传感器和记录它。
为了使这项工作我已经使用了request module。一切工作正常,当我在我的本地机器上测试它(我的额外层监听localhost:3000
和webapp监听localhost:3001
),但只要我指向外部URL我回来的答案是404 Not Found
,即使如果我直接POST到example2.com
一切都按预期工作。
这里是我的模块:
var express = require('express');
var app = express();
var request = require('request');
var bodyParser = require('body-parser');
var cuid = require('cuid');
var url = require('url');
app.use(bodyParser.text({ type: '*/*' }));
app.post('/', function (req, res) {
// immediately send 200 OK to the client
res.send('ok');
// add a unique ID
if (!req.headers['x-request-cuid']) {
req.headers['x-request-cuid'] = cuid();
}
var log_string = req.headers['x-request-cuid'] + "," + new Date().toISOString();
// filter empty requests
var reqbody = req.body;
if(typeof reqbody !== 'string'){
return res.send('empty body');
}
// Configure the request
var options = {
method: 'POST',
url: 'http://example.com', // <- if I put localhost:3001 (the port I put my webapp to listen on) here, it works
headers: req.headers,
body: reqbody
};
// Start the request
request(options, function (error, response, body) {
log_string += "," + new Date().toISOString() + "," + response.statusCode + "," + response.statusMessage + "," + response.body;
console.log(log_string);
});
});
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
如果有帮助,我在谷歌App Engine的工作,所以一切都被部署到谷歌应用程序引擎。
编辑:澄清“不工作”
你尝试加入'删除req.headers .host;'var options = ...之前''?另外,你应该在你的问题中解释更多关于“不起作用”的含义。 – mscdex
我马上试试。我也编辑了“不起作用” –