0

我正在构建一个应用程序,它将 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。这里有什么想法吗?

4

1 回答 1

0

我在这里发现了问题!问题是我需要专门将内容类型设置为

 application/json; charset=UTF-8

感谢这篇文章帮助我:

jQuery ajax,如何发送 JSON 而不是 QueryString

于 2015-01-03T15:57:58.093 回答