gpt4 book ai didi

javascript - NodeJS Ajax 未传递数组,错误 : "Unexpected token u in JSON at position 0"

转载 作者:行者123 更新时间:2023-12-03 01:33:02 25 4
gpt4 key购买 nike

我试图将带有 javascript 的数组传递到 Node.js 中的服务器,但收到此错误:

Unexpected token u in JSON at position 0

我查找了这个错误代码,发现这是因为我正在使用 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);
});

请求详细信息: enter image description here

最佳答案

如果您不使用主体解析器,则主体将是一个缓冲区。

我们需要:

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 

确保已安装。

关于javascript - NodeJS Ajax 未传递数组,错误 : "Unexpected token u in JSON at position 0",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51194551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com