我正在尝试使用节点将带有JSON有效负载的POST请求发送到外部API。
这是我的代码:
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var url = require("url");
var http = require("http");
var app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/api', function(req, res) {
var query = url.parse(req.url, true).query;
var key = query.key;
console.log('JSON PAYLOAD:');
console.log(req.body); **//PAYLOAD COMES THROUGH AS EXPECTED**
var options = {};
options = {
host: 'localhost',
port: 1234,
method: 'POST',
headers: {'Content-Type': 'application/json'},
path: '/api?key=1234'
};
var request = http.request(options, function(response) {
response.setEncoding('utf-8');
var responseString = '';
response.on('data', function(data) {
responseString += data;
});
response.on('end', function() {
var resultObject = JSON.parse(responseString);
res.json(resultObject);
});
});
request.on('error', function(e) {
});
request.write(req.body) **//THIS METHOD SHOULD BE FORWARDING THE PAYLOAD BUT THIS IS NOT THE CASE...**
request.end();
});
JSON有效负载按照预期从原点开始。但是,我无法将此有效负载转发到外部API。 ' request.write(req.body)'似乎是这样做的方式,但是外部API仍然接收空的有效负载。
任何帮助将不胜感激。感谢。
答案 0 :(得分:0)
在app.post块中试试这个
var options = {
host: 'localhost',
path: '/api?key=1234',
port: 1234,
method: 'POST',
headers: {'Content-Type': 'application/json'}
};
callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = http.request(options, callback);
req.write(JSON.stringify(req.body));
req.end();