【问题标题】:Setting content type for node JS http request为节点 JS http 请求设置内容类型
【发布时间】:2019-11-05 14:26:29
【问题描述】:

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

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();
}

当我通过 Postman 访问我的中间应用程序时,我从烧瓶 data = request.json['message']\nTypeError: 'NoneType' object is not subscriptable 收到以下错误消息。通过挖掘,问题似乎是当我发送请求时,没有设置内容类型,但是每当我尝试在我的选项标题中设置内容类型时,我都会遇到构建失败。我将如何为我的请求设置内容类型,以便它使用“应用程序/json”,或者这甚至不是我的问题?

【问题讨论】:

  • 我建议您在执行 POST 时查看 http.request() here 的示例代码。在我看来,您的操作并不正确。你错过了req.write(postData)
  • 实际上,您的链接让我找到了答案,我只需要 headers 选项来设置内容类型。现在我收到 400 错误,但它不同了 :)
  • 或者,使用比http.request()更简单的request library
  • A 400 错误(这是错误请求)很可能是因为您没有像我之前指出的那样发送带有 req.write(postData) 的帖子正文。
  • @jfriend00 我试试这个方法,谢谢!

标签: node.js http


【解决方案1】:

您需要写入请求对象以发送您的 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();
}

【讨论】:

    猜你喜欢
    • 2012-04-07
    • 2019-08-01
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多