簡體   English   中英

NodeJS Ajax沒有傳遞數組,錯誤:“ JSON在位置0處出現意外令牌u”

[英]NodeJS Ajax not passing array, error: “Unexpected token u in JSON at position 0”

我試圖將帶有javascript的數組傳遞到node.js中的服務器,並且我收到此錯誤:

JSON中位置0處的意外令牌u

我查找了此錯誤代碼,發現這是因為我正在使用Json解析未定義的內容。 我一定不能將數組正確傳遞到服務器。 我究竟做錯了什么? 這是我的代碼:

客戶端:

function ClientSide()
{
    var info = [];
    info[0] = 'hi';
    info[1] = 'hello';
    var json = JSON.stringify(info); //convert to json

    $.ajax({
        type: 'post',
        url: '/save',
        data: json,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (html) {
        }
    })
}

服務器端:

app.post('/save', function(req,res)
{
    var Passed_value = JSON.parse(req.body);
    console.log(Passed_value);
});

要求詳細信息: 在此處輸入圖片說明

如果您不使用主體解析器,則主體將是一個緩沖區。

我們需要:

https://github.com/expressjs/body-parser#bodyparsertextoptions

因此,請嘗試:

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/save', function(req,res)
{
    var Passed_value = req.body;
    console.log(Passed_value);
});

當然,您需要

npm install body-parser 

確保已安裝。

暫無
暫無

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

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