admin管理员组

文章数量:1406312

So I have on the client side within a controller:

 $scope.authenticate = function() {
            var creds = JSON.stringify({email: this.email, password: this.password});
            $http.post('/authenticate', creds).
                success(function(data, status, headers, config) {
                   // etc
                }).
                error(function(data, status, headers, config) {
                  // etc
                });
        };

And on the server side:

app.post('/authenticate', function(req, res) {
    console.log("Unserialized request: " + JSON.parse(req));
});

But I'm getting an error when I try to parse the request. I can't figure out why. Any ideas?

So I have on the client side within a controller:

 $scope.authenticate = function() {
            var creds = JSON.stringify({email: this.email, password: this.password});
            $http.post('/authenticate', creds).
                success(function(data, status, headers, config) {
                   // etc
                }).
                error(function(data, status, headers, config) {
                  // etc
                });
        };

And on the server side:

app.post('/authenticate', function(req, res) {
    console.log("Unserialized request: " + JSON.parse(req));
});

But I'm getting an error when I try to parse the request. I can't figure out why. Any ideas?

Share Improve this question asked Nov 14, 2013 at 1:30 Julian SutherlandJulian Sutherland 1032 silver badges5 bronze badges 1
  • 2 You probably don't want to parse the request object itself. You want to parse a field with in the body (req.body or req.body.whatever) – Hector Correa Commented Nov 14, 2013 at 1:33
Add a ment  | 

2 Answers 2

Reset to default 4

Use the express.bodyParser middleware which will do the parsing for you and give you req.body as an object ready to go.

var express = require('express');

app.post('/authenticate', express.bodyParser(), function(req, res) {
    console.log("Unserialized request: " + req.body);
});

To plete Peter Lyons' answer, I think you can use express.bodyParser(), but it's better if you use

[express.urlencoded(), express.json()]

in place of

express.bodyParser()

i.e.

app.post('/authenticate', [express.urlencoded(), express.json()], function(req, res) {
console.log("request body= " + req.body);
});

It also takes care of parsing the request. But, it's more secure and since you only need json and not any file. If you use bodyParser any one can send file as well, to your post request.

本文标签: javascriptHow to unserialize JSON data in ExpressNodejsStack Overflow