[英]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.