Reputation: 307
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);
});
Upvotes: 0
Views: 139
Reputation: 30725
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.
Upvotes: 1