张贴json表达 - 无效的json

时间:2014-07-14 11:34:34

标签: json node.js express

我试图将一些json发布到运行express的节点服务器,但它一直告诉我json无效。但它不是,它只是一个普通的旧物体。目前我收到错误'意外令牌i'

客户端:

$.ajax({
    contentType: 'application/json',
    type: "POST",
    url: "/admin",
    data: {id: '435ghgf545ft5345', allowed: true}
});

服务器:

var bodyParser = require('body-parser');
app.use(bodyParser({strict: false}));

app.post('/admin', function(request, response) {
    console.log(request.body);
});

我也尝试将bodyParser.json()作为后期路由中的第二个参数,并在解析时获得错误'invalid json'。我无法弄清楚原因。

1 个答案:

答案 0 :(得分:10)

此代码可以帮助您:

var jsondataResource = JSON.stringify({id: '435ghgf545ft5345', allowed: true});

$.ajax({
    type: 'POST', //GET or POST or PUT or DELETE verb
    async: false,
    url: '/admin', // Location of the service
    data: jsondataResource , //Data sent to server
    contentType: 'application/json', // content type sent to server
    dataType: 'json', //Expected data format from server
    processdata: true, //True or False
    crossDomain: true,
    success: function (msg, textStatus, xmlHttp) {
        result = msg;
    },
    error: ServiceFailed  // When Service call fails
});
function ServiceFailed(result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
Type = null; Url = null; Data = null; ContentType = null; DataType = null; ProcessData = null;
}