简体   繁体   中英

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

I am trying to pass an array with javascript to the server in node.js and i am recieving this error:

Unexpected token u in JSON at position 0

I looked up this error code and figured out that this is because i am using Json to parse something that's undefined. I must not be passing the array correctly to the server. What am i doing wrong? Here is my code:

Client Side:

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) {
        }
    })
}

Server Side:

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

Request Details: 在此处输入图片说明

If you're not using a body parser, the body will be a Buffer.

We need:

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

So try:

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

And of course, you'll need

npm install body-parser 

to ensure it's installed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM