我正在构建一个应用程序,它将 NSMutableURLRequest 中的 json 发送到我运行 Node 和 Express 的服务器。
JSON 有效负载在节点中打印出来,如下所示:
{ '{"firstName":"Scotty","lastName":"Lastname","profileId":"123454321234"}': '' }
我的节点代码如下所示
var http = require("http");
var express = require("express");
var bodyParser = require('body-parser');
var mongoose = require("mongoose");
var remote_db_url = require('./database.js');
mongoose.connect(remote_db_url.url);
var user = require('./user.model.js');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var user_data = new user();
app.post("/account/login", function(req,res)
{
var user = req.body;
console.log("user is: "+ user);
console.log("firstname is: " + user.firstName);
user_data.save(function(err,suc) {
if (err)
res.json({"status" : 400,"error":"Bad request"});
else
res.json({"status":200,"id" : suc.id });
});
});
控制台日志语句显示如下:
user is: { '{"firstName":"Scotty","lastName":"Lastname","profileId":"123454321234"}': '' }
firstname is: undefined
我通过 charles 进行代理,可以确认有效负载如下所示:
POST /account/login HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Connection: keep-alive
Accept: */*
User-Agent: test/1 CFNetwork/711.1.12 Darwin/14.0.0
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Content-Length: 79
Host: 192.168.1.4:3000
{"firstName":"Scotty","lastName":"Lastname","profileId":"123454321234"}
我似乎无法正确解析 json。这里有什么想法吗?