简体   繁体   中英

Can't parse JSON after sending it via Ajax request

Client side

After applying JSON.stringy to an object it is sent like this to a node-server (as POST-request):

{"id":"topFolder","parentPath":null,"name":"newProject","is":"root","children":[]}

I'm sending the request on the client via Polymer's iron-ajax-element: <iron-ajax id="ajaxSave" method="POST" url="/save" handle-as="json" on-response="doit" </iron-ajax>

It is sent with this function:

save: function() {
  var v = JSON.stringify(this.data);
  this.$.ajaxSave.body = v;
  this.$.ajaxSave.generateRequest();
}

Server side

Then I try to JSON.parse the request's body on the Koa-server (using Koa-Body as the body parser):

router.post('/save', body, function*(){
  let data = JSON.parse(this.request.body);
  this.body = "all ok";
})

I get a SyntaxError: Unexpected token o and the raw body looks like this:

{ '{"id":"topFolder","parentPath":null,"name":"new Project","is":"root","children":': [ '' ] }

Why does the received body look different and how can I fix it?

Edit: This is a full curl-command of the request:

curl ' http://localhost:3000/save ' -H 'Authorization: Basic YWRtaW46ZXZvbGE=' -H 'Origin: http://localhost:3000 ' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36' -H 'content-type: application/x-www-form-urlencoded' -H 'accept: application/json' -H 'Referer: http://localhost:3000/ ' -H 'Cookie: ajs_anonymous_id=%22e43155da-6541-45de-af9f-046ff5ac7b3c%22; currentUserId=34; -H 'Connection: keep-alive' --data '{"id":"topFolder","open":false,"parentPath":null,"name":"new Project","children":[]}' --compressed

Your object is already an object.

JSON.parse() is used to convert a string containing JSON notation into a Javascript object.

For example, try: this.request.body["id"] to get one of properties.

The problem was that the content-type was set to application/x-www-form-urlencoded . It has to be application/json

Usually body is not a string, so try to explicitly turn it into one.

body.toString()

If it doesn't help... In some transport libraries you have to read body prior to use it by calling body.read(). Read operation can be async..

With q-io it looks like

request(someURL)
.then( function(res) {
  return res.body.read() 
})
.then( function (body){
  obj = JSON.parse(body.toString()
})

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