通过Ajax请求发送后无法parsingJSON
客户端
在将JSON.stringy
应用到对象之后,将它像这样发送到节点服务器(作为POST请求):
{"id":"topFolder","parentPath":null,"name":"newProject","is":"root","children":[]}
我通过Polymer的iron-ajax元素在客户端发送请求: <iron-ajax id="ajaxSave" method="POST" url="/save" handle-as="json" on-response="doit" </iron-ajax>
它是用这个函数发送的:
save: function() { var v = JSON.stringify(this.data); this.$.ajaxSave.body = v; this.$.ajaxSave.generateRequest(); }
服务器端
然后我尝试在Koa-server上使用JSON.parse
请求的正文(使用Koa-Body作为正文parsing器):
router.post('/save', body, function*(){ let data = JSON.parse(this.request.body); this.body = "all ok"; })
我得到一个SyntaxError: Unexpected token o
和原始的机构看起来像这样:
{ '{"id":"topFolder","parentPath":null,"name":"new Project","is":"root","children":': [ '' ] }
为什么收到的身体看起来不同,我该如何解决?
编辑:这是一个完整的curl命令的请求:
curl'http :// localhost:3000 / save'-H'Authorization:Basic YWRtaW46ZXZvbGE ='-H'Origin: http:// localhost: 3000'-H'Accept-Encoding:gzip,deflate'-H'Accept-用户代理:Mozilla / 5.0(Macintosh; Intel Mac OS X 10_11_2)AppleWebKit / 537.36(KHTML) ,如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”:[]} “ – 压缩
你的对象已经是一个对象。
JSON.parse()
用于将包含JSON表示法的string转换为Javascript对象。
例如,尝试: this.request.body["id"]
来获取其中一个属性。
问题是content-type
被设置为application/x-www-form-urlencoded
。 它必须是application/json
通常body不是一个string,所以试着明确地把它变成一个。
body.toString()
如果它没有帮助…在一些传输库中,你必须通过调用body.read()来读取body。 读操作可以是asynchronous的
用q-io看起来像
request(someURL) .then( function(res) { return res.body.read() }) .then( function (body){ obj = JSON.parse(body.toString() })