我正处于 NodeJs 的学习阶段,我试图从 URL 中传递的 json 中获取参数值。我正在使用正文解析器,因为我看到许多堆栈溢出答案都使用它来解析数据。
下面是我传递的 URL,
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);
关于javascript - SyntaxError : Unexpected token u at Object. 为 JSON.parse() 解析( native )NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34355770/