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
2 Answers
Reset to default 4Use 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
版权声明:本文标题:javascript - How to unserialize JSON data in ExpressNode.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745005416a2637232.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论