我正处于NodeJs的学习阶段,我试图从URL中传递的json中获取参数值.我正在使用body解析器,因为我看到许多堆栈溢出答案使用相同来解析数据.
以下是我通过的网址,
http://localhost:1337/login?json={username:rv,password:password}
我收到下面提到的错误,
SyntaxError: Unexpected token u at Object.parse (native) at C:\Users\summer\Desktop\nodejs\practise3.njs:14:17 at Layer.handle [as handle_request] (C:\Users\summer\Desktop\nodejs\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\summer\Desktop\nodejs\node_modules\express\lib\router\route.js:131:13) at Route.dispatch (C:\Users\summer\Desktop\nodejs\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\Users\summer\Desktop\nodejs\node_modules\express\lib\router\layer.js:95:5) at C:\Users\summer\Desktop\nodejs\node_modules\express\lib\router\index.js:277:22 at Function.process_params (C:\Users\summer\Desktop\nodejs\node_modules\express\lib\router\index.js:330:12) at next (C:\Users\summer\Desktop\nodejs\node_modules\express\lib\router\index.js:271:10) at jsonParser (C:\Users\summer\Desktop\nodejs\node_modules\body-parser\lib\types\json.js:100:40)
代码如下所述,
var express = require('express'); var http = require('http'); var app = express(); var bodyparser = require('body-parser'); app.use(bodyparser.json()); app.get('/login',function(req,res,next){ var content = ''; var data = ''; data = req.query.json; content = JSON.parse(data); //I am getting the error here res.writeHead(200,{"Content-type":"text/plain"}); res.write(data); res.end(); }); http.createServer(app).listen(1337); console.log("Server Started successfully at Port 1337");
注意:阅读完这个问题之后,如果你知道从json数据中收集值的其他选择,请告诉我们.
而不是这个:
data = req.query.json; content = JSON.parse(data); //I am getting the error here
试试这个:
data = req.query.json; var stringify = JSON.stringify(data) content = JSON.parse(stringify);
JSON.parse
因为与Javascript不同,JSON要求所有的键名都在引号[0]中,所以你的JSON应该是
{"username":rv,"password":password}
当JSON解析器遇到"用户名"开头的"u"时,会发生错误"Unexpected token u ...",当时它需要一个引号.
[0]在http://json.org上有一个非常易读的JSON规范摘要.