node js request.post回调未触发

时间:2016-12-28 23:30:34

标签: node.js express http-post httprequest

我正在尝试将一些JSON数据从节点js app发送到另一个用Flask编写的Web服务。我正在尝试使用请求库并查看问题herehere

基于这些例子,我提出了以下简单的应用程序。该应用程序将JSON数据发送到我的烧瓶服务器,但不会获取/触发回调。我检查过Flask应用程序通过postman返回一些数据,它运行正常。 我哪里错了?

[这是我的整个app.js]

  var express = require("express");
  var request = require('request');
  var app = express();

  app.set('view engine', 'pug');
  app.get('/', function(req, res) {
    console.log("here...")
      request({
          url: 'http://localhost:5000/receive_user_response',
          method: "POST",
          headers: {
              "content-type": "application/json"
          },
          json: {  // <--- I have also tried calling this as "body" 
              user_id: "some id...",
              user_info: "some info..."
          },
        function(err, res, data) {
            console.log('err', err) // <---- never prints any thing from here!
            console.log('res', res)
            console.log('data', data)
              if (!err && res.statusCode == 200) {
                  console.log(data);
              }
          }
    })
    console.log("here...done..")
  });

  var server = app.listen(3000, function() {
      console.log("Listening on port %s...", server.address().port);
  });

2 个答案:

答案 0 :(得分:0)

这不是真正的答案,但我可以使用request-promise代替请求让它工作。

system()

答案 1 :(得分:0)

回调函数必须是request函数的第二个参数。您不小心将它放在json对象中。以下是可行的。

request({
    url: 'http://localhost:5000/receive_user_response',
    method: "POST",
    headers: {
      "content-type": "application/json"
    },
    json: {  // <--- I have also tried calling this as "body" 
      user_id: "some id...",
      user_info: "some info..."
    }
  },
  function(err, res, data) {
    console.log('err', err) // <---- never prints any thing from here!
    console.log('res', res)
    console.log('data', data)
    if (!err && res.statusCode == 200) {
      console.log(data);
    }
  }
)

但这绝对是更好的阅读。

let options = {
  url: 'http://localhost:5000/receive_user_response',
  method: "POST",
  headers: {
    "content-type": "application/json"
  },
  json: {  // <--- I have also tried calling this as "body" 
    user_id: "some id...",
    user_info: "some info..."
  }
};


request(options,
  function(err, res, data) {
    console.log('err', err) // <---- never prints any thing from here!
    console.log('res', res)
    console.log('data', data)
      if (!err && res.statusCode == 200) {
        console.log(data);
      }
  }
)