如何从节点后端的 $http.post/angular 检索 post 变量?

How do I retrieve the post variables from $http.post/angular on my node backend?

这是我的前端。

auth
var time = 5;

$http.post('/tasks/addTime', null, {
    headers: {
        Authorization: "Bearer " + auth.getToken()
    },
    data: {
        id: "Me",
        time: time,
    }
});

这是背面

router.post('/tasks/addTime', auth, function(req, res, next) {
    console.log(req);
});

我能够看到数据结构 req 被回显,所以我正在正确调用后端。我如何访问我的 "id" 和 "time" 变量?

节点以块的形式处理 POST 数据。您的函数需要接收数据块并构建一个完整的主体。有诸如 Express 之类的框架可以为您处理此问题,但以下是您自己如何处理此问题的示例:

router.post('/tasks/addTime', auth, function(req, res, next) {
  var body = "";
  req.on('data', function (chunk) {
    body += chunk;
  });
  req.on('end', function () {
    console.log('POSTed: ' + body);
  });
});

重要的是要注意,在侦听 POST 数据时,req 对象也是一个 Event Emitter。因此,req 将在收到 chunk 传入数据时发出 'data' 事件;当没有更多传入数据时,将发出 'end' 事件。因此,在我们的例子中,我们监听 'data' 事件。收到所有数据后,我们将数据记录到控制台。

使用 Express,您还应该有一个额外的对象,req.params

req.params

An object containing properties mapped to the named route “parameters”. For example, if you have the route /user/:name, then the “name” property is available as req.params.name. This object defaults to {}.

您还可以在 Express 中间件的帮助下使用 req.body

req.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.