简体   繁体   中英

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

Here is my front end.

auth
var time = 5;

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

Here is the back

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

I am able to see the data structure req is echoed so I am calling the backend properly.. how do I get access to my "id" and "time" variables?

Node processes POST data in chunks. Your function needs to receive the chunks of data and build a complete body. There are frameworks such as Express which will handle this for you, but the following is an example of how to do this yourself:

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

It is important to note, when listening for POST data, that the req object is also an Event Emitter . req , therefore, will emit a 'data' event whenever a chunk of incoming data is received; when there is no more incoming data, the 'end' event is emitted. So, in our case, we listen for 'data' events. Once all the data is recieved, we log the data to the console.

Using Express, you should also have an extra object, 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 {} .

You can also use req.body with the help of an Express middleware:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM