JSON.parse 意外的令牌 xmlhttprequest 和 node.js
JSON.parse Unexpected Token xmlhttprequest and node.js
我正在尝试将一个数字从 javascript 文件发送到 node.js 服务器(安装了 express 和 body-parser 模块),做一个小计算然后 return结果,更新了一个 html 字段。我收到以下错误:Unexpected token 0 in JSON at position 0,即使在删除代码中的所有 JSON.stringify 和 JSON.parse 命令之后也是如此。
正在使用以下文件(在根目录 /app 中 index.js):
index.js
//////////////////// Module Initializations ////////////////////
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
//////////////////// Backend Functions ////////////////////
function secret_calculation(num)
{
var result = num * 5;
return result;
}
//////////////////// Running Server ////////////////////
app.use(express.static(__dirname + '/Static'));
app.get('/',function(req,res){
res.sendFile('Static/app.html', {root : __dirname});
});
app.listen(3000);
console.log('\n\n -------- S E R V E R R U N N I N G -------- \n\n');
//////////////////// Settings for Data Transfer ////////////////////
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json());
app.use(function (req, res, next) {
// to restrict api calls to the ones coming from your website
res.append('Access-Control-Allow-Origin', 'http://localhost:3000');
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
});
//////////////////// AJAX Requests ////////////////////
app.post("/num", function(req, res) {
var num = parseInt(JSON.parse(req.body));
result = secret_calculation(num);
res.send(JSON.stringify(result));
});
Static/client_server_comms.js
function request_handler(theUrl, data, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
callback(JSON.parse(xmlHttp.responseText));
}
}
xmlHttp.open('POST', theUrl, true); // true for asynchronous
xmlHttp.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
xmlHttp.send(JSON.stringify(data));
}
function secret_calculation_(num, ans)
{
request_handler("/num", num, function(result) {ans.innerHTML = result;});
}
Static/app.js
document.getElementById("button1").addEventListener("click", get_input);
function get_input()
{
user_input = parseInt(document.getElementById("in_put").value);
user_input = user_input || 0;
ans = document.getElementById("answer");
secret_calculation_(user_input, ans);
}
Static/app.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input id="in_put" type="text" maxlength="3" size="5" oninput="this.value = this.value.replace(/[^0-9]/g, '');" >
<span> x 5 = </span><span id="answer"></span>
<br><br>
<input type="button" id="button1" value="Calculate">
<script src="app.js"></script>
<script src="client_server_comms.js"></script>
</body>
</html>
JSON 尝试解析的格式似乎有问题(发生在 xmlhttprequest 和 app.post 之间)。我在堆栈交换上应用了类似问题的解决方案,但没有骰子。
错误:
SyntaxError: Unexpected token 0 in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (/Users/Mick/Desktop/app/node_modules/body-parser/lib/types/json.js:158:10)
at parse (/Users/Mick/Desktop/app/node_modules/body-parser/lib/types/json.js:83:15)
at /Users/Mick/Desktop/app/node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/Users/Mick/Desktop/app/node_modules/raw-body/index.js:224:16)
at done (/Users/Mick/Desktop/app/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/Users/Mick/Desktop/app/node_modules/raw-body/index.js:273:7)
at emitNone (events.js:106:13)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
您似乎没有按要求传递 JSON 数据。如果您的 num = 5 那么您将 JSON.stringify(5) 作为 req.body 传递,这是无效的 JSON。
请看客户端修改后的代码:
function request_handler(theUrl, data, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
callback(JSON.parse(xmlHttp.responseText));
}
}
xmlHttp.open('POST', theUrl, true); // true for asynchronous
xmlHttp.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
//xmlHttp.send(JSON.stringify(data));
xmlHttp.send(JSON.stringify({num: data}))
}
function secret_calculation_(num, ans)
{
request_handler("/num", num, function(data) {ans.innerHTML = data.result;});
}
在 app.post("/num") 内的服务器端,使用以下内容:
app.post("/num", function(req, res) {
var data = validateJSON(req.body);
var num = parseInt(data.num);
result = secret_calculation(num);
res.send(JSON.stringify({ result: result }));
});
其中 validateJSON 是一个函数,可以定义为:
function validateJson(data){
var jsonData;
try {
jsonData = JSON.parse(data);
} catch (e) {
console.log(e.message);
jsonData = data;
}
return jsonData;
};
我正在尝试将一个数字从 javascript 文件发送到 node.js 服务器(安装了 express 和 body-parser 模块),做一个小计算然后 return结果,更新了一个 html 字段。我收到以下错误:Unexpected token 0 in JSON at position 0,即使在删除代码中的所有 JSON.stringify 和 JSON.parse 命令之后也是如此。
正在使用以下文件(在根目录 /app 中 index.js):
index.js
//////////////////// Module Initializations ////////////////////
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
//////////////////// Backend Functions ////////////////////
function secret_calculation(num)
{
var result = num * 5;
return result;
}
//////////////////// Running Server ////////////////////
app.use(express.static(__dirname + '/Static'));
app.get('/',function(req,res){
res.sendFile('Static/app.html', {root : __dirname});
});
app.listen(3000);
console.log('\n\n -------- S E R V E R R U N N I N G -------- \n\n');
//////////////////// Settings for Data Transfer ////////////////////
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json());
app.use(function (req, res, next) {
// to restrict api calls to the ones coming from your website
res.append('Access-Control-Allow-Origin', 'http://localhost:3000');
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
});
//////////////////// AJAX Requests ////////////////////
app.post("/num", function(req, res) {
var num = parseInt(JSON.parse(req.body));
result = secret_calculation(num);
res.send(JSON.stringify(result));
});
Static/client_server_comms.js
function request_handler(theUrl, data, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
callback(JSON.parse(xmlHttp.responseText));
}
}
xmlHttp.open('POST', theUrl, true); // true for asynchronous
xmlHttp.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
xmlHttp.send(JSON.stringify(data));
}
function secret_calculation_(num, ans)
{
request_handler("/num", num, function(result) {ans.innerHTML = result;});
}
Static/app.js
document.getElementById("button1").addEventListener("click", get_input);
function get_input()
{
user_input = parseInt(document.getElementById("in_put").value);
user_input = user_input || 0;
ans = document.getElementById("answer");
secret_calculation_(user_input, ans);
}
Static/app.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input id="in_put" type="text" maxlength="3" size="5" oninput="this.value = this.value.replace(/[^0-9]/g, '');" >
<span> x 5 = </span><span id="answer"></span>
<br><br>
<input type="button" id="button1" value="Calculate">
<script src="app.js"></script>
<script src="client_server_comms.js"></script>
</body>
</html>
JSON 尝试解析的格式似乎有问题(发生在 xmlhttprequest 和 app.post 之间)。我在堆栈交换上应用了类似问题的解决方案,但没有骰子。
错误:
SyntaxError: Unexpected token 0 in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (/Users/Mick/Desktop/app/node_modules/body-parser/lib/types/json.js:158:10)
at parse (/Users/Mick/Desktop/app/node_modules/body-parser/lib/types/json.js:83:15)
at /Users/Mick/Desktop/app/node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/Users/Mick/Desktop/app/node_modules/raw-body/index.js:224:16)
at done (/Users/Mick/Desktop/app/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/Users/Mick/Desktop/app/node_modules/raw-body/index.js:273:7)
at emitNone (events.js:106:13)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
您似乎没有按要求传递 JSON 数据。如果您的 num = 5 那么您将 JSON.stringify(5) 作为 req.body 传递,这是无效的 JSON。
请看客户端修改后的代码:
function request_handler(theUrl, data, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
callback(JSON.parse(xmlHttp.responseText));
}
}
xmlHttp.open('POST', theUrl, true); // true for asynchronous
xmlHttp.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
//xmlHttp.send(JSON.stringify(data));
xmlHttp.send(JSON.stringify({num: data}))
}
function secret_calculation_(num, ans)
{
request_handler("/num", num, function(data) {ans.innerHTML = data.result;});
}
在 app.post("/num") 内的服务器端,使用以下内容:
app.post("/num", function(req, res) {
var data = validateJSON(req.body);
var num = parseInt(data.num);
result = secret_calculation(num);
res.send(JSON.stringify({ result: result }));
});
其中 validateJSON 是一个函数,可以定义为:
function validateJson(data){
var jsonData;
try {
jsonData = JSON.parse(data);
} catch (e) {
console.log(e.message);
jsonData = data;
}
return jsonData;
};