设置节点JS http请求的内容类型

我正在使用Node.js开发一个简单的应用程序,以充当编排层来拦截请求并将其发送到另一个并行运行的应用程序(我的中间应用程序位于端口8000上,并通过API {{1 }},然后将请求路由到在端口5000 /interceptMessage上的其他应用程序中本地运行的另一个API。我已经设置了整个应用程序,但是我遇到了通过http POST请求调用第二个应用程序的问题。这是我的Controller.js代码:

/processMessage

当我通过Postman打我的中间应用程序时,我从烧瓶exports.postToClient = function(req,res) { var http = require('http'); var options = { host: 'localhost',port: 5000,path: '/processMessage',method: 'POST',accept: 'application/json',//For testing,will use the request's JSON eventually json: { "message":"Hello" } }; console.log(JSON.stringify(options)); http.request(options,function(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data',function (chunk) { console.log('BODY: ' + chunk); }); }).end(); } 中收到以下错误消息。从深入研究来看,问题似乎是当我发送请求时,没有设置内容类型,但是任何时候我尝试在选项标头中设置内容类型时,都会出现构建失败。我该如何为请求设置内容类型,使其使用'application / json',还是我的问题呢?

wwjazrael 回答:设置节点JS http请求的内容类型

您需要写入请求对象以发送POST数据:

exports.postToClient = function(req,res) {
    var http = require('http');

    var options = {
      host: 'localhost',port: 5000,path: '/processMessage',method: 'POST',accept: 'application/json',};
    console.log(JSON.stringify(options));
    let req = http.request(options,function(res) {
      console.log('STATUS: ' + res.statusCode);
      console.log('HEADERS: ' + JSON.stringify(res.headers));
      res.setEncoding('utf8');
      res.on('data',function (chunk) {
        console.log('BODY: ' + chunk);
      });
    });
    req.on('error',(e) => {
        console.error(`problem with request: ${e.message}`);
    });
    req.write(/* properly formatted/encoded post data here */);
    req.end();
}
本文链接:https://www.f2er.com/3163267.html

大家都在问