我正在本地计算机上运行一个运行express.js的node.js服务器,需要对客户端发出的请求进行解码,该请求中包含json字符串。我运行下面的代码,并收到以下错误。
SyntaxError: Unexpected token v in JSON at position 2
at JSON.parse (<anonymous>)
at C:\myLocation\source\repos\server\server\server.js:144:19
at Layer.handle [as handle_request] (C:\myLocation\source\repos\server\server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\myLocation\source\repos\server\server\node_modules\express\lib\router\index.js:317:13)
我的要求是
http://localhost:1337/%7B%22Code%22:%22VNdVwY9iWhFZ114CjcDZbY%22,%22Chat%22:%22Test.txt%22%7D
预期的json是
{“代码”:“ VNdVwY9iWhFZ114CjcDZbY”,“聊天”:“ Test.txt”}
我得到了json,但它仍然给我同样的错误。
我的代码:
app.use(function (req, res) {
//console.log(req.url)
var myStr = req.url.replace('/', '')
if (myStr != false) {
let decodeStr = decodeURIComponent(myStr)
var test = JSON.parse(decodeStr)
var json = JSON.stringify(test)
if (json.includes(createkey)) {
console.log("Create: " + json)
createFile(req, res, test)
} else if (json.includes(modKey)) {
console.log("Modify: " + json)
modifyFile(req, res, test)
} else if (json.includes(readFileKey)) {
console.log("Read: " + json)
readFile(req, res, test)
}
} else {
res.sendStatus(404)
console.log("home")
}
})
为什么会出现错误?
编辑1
我添加了console.log(decodeStr)
,但仍然出现错误。返回{"Code":"VNdVwY9iWhFZ114CjcDZbY","Chat":"Test.txt"}
{“代码”:“'GAHGAaphgAP:gjpaGHAHAG {AaGRAP; GHPG; RA”,“ Chat”:“ Test.txt”}不是有效的json,这就是您遇到该错误的原因,相反,您可以解析
JSON.parse('{"Code":"\'GAHGAaphgAP:gjpaGHAHAG{AaGRAP;GHPG;RA","Chat":"Test.txt"}')
尝试
var uri = "http://localhost:1337/%7B%22Code%22:%22%5C'GAHGAaphgAP:gjpaGHAHAG%7BAaGRAP;GHPG;RA%22,%22Chat%22:%22Test.txt%22%7D";