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: enter image description here

Community
  • 1
  • 1
Some_Dude
  • 309
  • 5
  • 21
  • 1
    What does `console.log(req.body)` say? Are you using body parser? – Mark Jul 05 '18 at 15:04
  • 1
    From the error is seems to me that the server already does the parsing for you, so you don't need JSON.parse on the req.body – Orr Siloni Jul 05 '18 at 15:05
  • @Mark_M It breaks before then on "var Passed_value = JSON.parse(req.body);" I get the error code: "SyntaxError: Unexpected token u in JSON at position 0". It seems the array isnt being passed and that i am parsing undefined. – Some_Dude Jul 05 '18 at 15:06
  • 1
    @Some_Dude I was asking about the value of `req.body` have you looked at that? – Mark Jul 05 '18 at 15:07
  • 1
    What response do you actually receive from the server ("response" tab in Chrome) ? Because you're not responding to the browser at all in your server code. – Jeremy Thille Jul 05 '18 at 15:07
  • @Mark_M Ok, sorry. Yes, it says it is undefined. – Some_Dude Jul 05 '18 at 15:08
  • 1
    Okay, it sounds like you might not be using body parser. See also: https://stackoverflow.com/questions/24543847/req-body-empty-on-posts – Mark Jul 05 '18 at 15:08
  • 1
    Also, stringifying in the browser and re-parsing on the server is totally useless. Send JSON/Array/Object, receive JSON/Array/Object directly. – Jeremy Thille Jul 05 '18 at 15:09
  • 1
    @Mark_M, Thanks! I added "app.use(bodyParser.json())" to my code and now i am receiving the array. – Some_Dude Jul 05 '18 at 15:13

1 Answers1

1

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.

Terry Lennox
  • 29,471
  • 5
  • 28
  • 40