我正在尝试从 JavaScript
发送 PUT
请求。我无法将值从 javascript
发送到 node js
,它给了我编辑: error is Unexpected token: o at Object.parse()
。在这一行 var message = JSON.parse(req.responseText);
也许我应该提到我正在使用 bodyParser。
request.open("PUT", "myurl", true);
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify({message: "from javascript"}));
来自 node js
我想将该值发送到 couchDB
,但我不确定如何获取从 传递的
message
值>javascript
router.put('/fillMessage', function(req, res){
var request = new XMLHttpRequest();
//...
var message = req.body;
var newData = {_id: data._id, _rev: data._rev, message: "JS value goes here"};
//...
});
现在我正在调试 Node js req
变量,似乎没有 json 值传递到其中。没有 responseText
或 body
属性
最佳答案
大多数情况下,Unexpected token: o at Object.parse()
意味着您尝试解析的内容都不是 JSON 编码的字符串。它可能已经是一个对象,例如 JSON.parse({ Two : 2 })
给出了相同的错误。
JSON.parse 尝试将输入转换为字符串,然后将其解析为 JSON,因此在
var foo = { two : 2 };
JSON.parse(foo); // throws, equivalent to JSON.parse("[object Object]")
使用 JSON.parse
时,最好先检查 req.responseText
是否为字符串,然后包装 JSON.parse
在 try/catch block 中。
关于javascript - Node js,使用 couchdb 发出请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34952071/