javascript - SyntaxError : Unexpected token u at Object. 为 JSON.parse() 解析( native )NodeJS

标签 javascript json node.js parsing

我正处于 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/

相关文章:

javascript - 从变量创建对象 ES6

javascript - Vue/Vuetify - 未知的自定义元素 : <v-app> - did you register the component correctly?

javascript - Reddit 搜索 API 网址?

javascript - 将选项卡重定向到我的页面的 Chrome 扩展

json - 为什么 JSON.NET 添加所有这些反斜杠

node.js - 从自定义路径预加载 env 文件

node.js - 在 winston 中使用自定义格式化程序记录错误

javascript - 是否可以在不使用服务器端技术的情况下将数据以文件形式存储到服务器

javascript - 如何使用 JQUERY 为多个 DIVS 内的按钮编写 CLICK 函数

javascript - Yeoman Javascript错误涉及 'mkdir'