如何在 Express/Node.js 中反序列化 JSON 数据

How to unserialize JSON data in Express/Node.js

本文关键字:反序列化 JSON 数据 js Node Express      更新时间:2023-09-26

所以我在控制器中的客户端:

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

在服务器端:

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

但是当我尝试解析请求时出现错误。我不知道为什么。有什么想法吗?

使用 express.bodyParser 中间件,它将为您执行解析,并为您提供req.body作为准备就绪的对象。

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

要完成 Peter Lyons 的回答,我认为您可以使用 express.bodyParser(),但最好使用

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

代替

express.bodyParser()

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

它还负责分析请求。但是,它更安全,因为您只需要 json 而不是任何文件。如果您使用 bodyParser,任何人都可以将文件发送到您的 post 请求。