Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert object to primitive value

I post data to node server:

{
  "form_1": [{
    "resultName": "",
    "level": "",
    "unitOrder": "",
    "winner": "",
    "winnerOrder": "",
    "date": "1",
    "score": ""
  }],
  "form_2": [{
    "resultName": "",
    "level": "",
    "unitOrder": "",
    "winner": "",
    "winnerOrder": "",
    "date": "1",
    "score": ""
  }],
  "form_3": [{
    "resultName": "",
    "level": "",
    "unitOrder": "",
    "winner": "",
    "winnerOrder": "",
    "date": "1",
    "score": ""
  }]
}

And I try to console.log the data in express server:

console.log(req.body)

but there comes the error:

TypeError: Cannot convert object to primitive value

I do not understand. so how can I get the data ?

like image 825
laoqiren Avatar asked Dec 15 '16 12:12

laoqiren


1 Answers

The actual reason behind this error

when Javascript is trying to cast an object to a string.

Javascript will try to call the toString() method of that object. most of the Javascript objects have toString() method inherited from Object.prototype. but some of them that have a null prototype, not have toString() method so the Javascript will fail to convert those objects to a string primitive. and can't convert object to primitive error will rise.

to create a null prototype Object in Javascript use this method

let travel = Object.create(null);

The solution

travel = {...travel};
like image 109
TheEhsanSarshar Avatar answered Sep 28 '22 06:09

TheEhsanSarshar