簡體   English   中英

JSON字符串上的JSON解析拋出“無法將對象轉換為原始值”

[英]JSON parse on a JSON string throws “Cannot convert object to primitive value”

server.js

使用主體解析器中間件,車把和快遞

路線

module.exports = function (app) {
    app.post('/questionnaire/submit', function (req, res) { // Ajax Call
        var data = JSON.parse(req.body);
        res.send({});
    });
};

客戶

function submitData() { // Send a data object to the server
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        dataType: "json",
        data: JSON.stringify({
            satisfactory: "text 1",
            improvement: "text 2",
            rating: 0.7
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}

記錄req.body我得到一個JSON字符串

{'{“滿意”:“文本1”,“改進”:“文本2”,“等級”:0.7}':“”}

我嘗試將此字符串解析為一個對象。 這樣做時,我會收到此錯誤消息

  TypeError: Cannot convert object to primitive value at JSON.parse (<anonymous>) at C:\\Users\\mah\\Desktop\\FeedbackTool\\Server\\Routes\\questionnaire.js:12:25 at Layer.handle [as handle_request] (C:\\Users\\mah\\node_modules\\express\\lib\\router\\layer.js:95:5) at next (C:\\Users\\mah\\node_modules\\express\\lib\\router\\route.js:137:13) at Route.dispatch (C:\\Users\\mah\\node_modules\\express\\lib\\router\\route.js:112:3) at Layer.handle [as handle_request] (C:\\Users\\mah\\node_modules\\express\\lib\\router\\layer.js:95:5) at C:\\Users\\mah\\node_modules\\express\\lib\\router\\index.js:281:22 at Function.process_params (C:\\Users\\mah\\node_modules\\express\\lib\\router\\index.js:335:12) at next (C:\\Users\\mah\\node_modules\\express\\lib\\router\\index.js:275:10) at C:\\Users\\mah\\node_modules\\body-parser\\lib\\read.js:130:5 

那么如何將字符串解析為對象呢?

通常我會執行JSON.parse(req.body)

由於您正在使用body-parser中間件,因此您req.body再次解析req.body ,因為它已經由body-parser進行了body-parser

如果您使用了app.use(bodyParser.json())

那么你只需要這樣做

module.exports = function (app) {
    app.post('/questionnaire/submit', function (req, res) { // Ajax Call
        var data = req.body; // this is already parsed and is an object
        res.send({});
    });
};

正如@TJ Crowder指出的那樣,您還應該發送正確的contentType以便body-parser知道其json

function submitData() { // Send a data object to the server
    $.ajax({
        type: 'POST',
        url: '/questionnaire/submit',
        contentType: 'application/json',
        data: JSON.stringify({
            satisfactory: "text 1",
            improvement: "text 2",
            rating: 0.7
        })
    }).done(function () {
        $(location).attr('href', '/sendOff');
    }).fail(function () {

    });
}

dataType不會說您要發送什么類型的數據,它會說您期望什么類型的響應。 您需要說您正在通過ajax調用中的contentType: "application/json"發送JSON。 文檔中的詳細信息。 (到目前為止,您不是第一個或唯一一個被dataType命名的人。)

那是問題的一半。 另一半見Stamos的回答

您需要設置正確的contentType:

$.ajax({
    type: 'POST',
    url: '/questionnaire/submit',
    contentType: 'application/json',
    data: JSON.stringify({ satisfactory: "text 1", rating: 0.7 })
});


app.post('/questionnaire/submit', function (req, res) { // Ajax Call
    var data = JSON.parse(req.body);
    console.log(data.rating); // 0.7
    res.send(data);
});

另外,使用body-parser可以避免在服務器端link上進行JSON.parse調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM