【问题标题】:posting json to express - invalid json发布 json 来表达 - 无效的 json
【发布时间】:2014-09-04 07:35:00
【问题描述】:

我正在尝试将一些 json 发布到运行 express 的节点服务器,但它一直告诉我 json 无效。但它不是,它只是一个普通的旧物体。目前我收到错误'unexpected token 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() 作为第二个参数放在 post 路由中,并得到错误 'invalid json at parse'。我不知道为什么。

【问题讨论】:

    标签: json node.js express


    【解决方案1】:

    此代码可能对您有所帮助:

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

    【讨论】:

    • 嘿Sambath,谢谢你,事实上我没有对我的json进行字符串化,所以服务器试图解析一个已经解析过的对象。
    • 请不要随便发布任意的sn-p代码。您需要解释为什么这是正确的以及 OP 做错了什么。
    • 这是 jQuery 文档中的一个遗漏,还是只是 express 和 bodyparser 的一个特点?通过jquery post发送时是否需要对所有json对象进行字符串化? api.jquery.com/jquery.post 显示了一个带有 $.post( "test.php", { name: "John", time: "2pm" }) .done(function( data ) { alert( "Data Loaded: " + data ); }); 的示例
    猜你喜欢
    • 2013-05-06
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    • 2011-11-01
    • 2015-12-22
    • 2012-05-11
    • 1970-01-01
    相关资源
    最近更新 更多