【问题标题】:JSON.parse Unexpected Token xmlhttprequest and node.jsJSON.parse Unexpected Token xmlhttprequest 和 node.js
【发布时间】:2019-03-03 11:25:59
【问题描述】:

我正在尝试将一个数字从 javascript 文件发送到 node.js 服务器(安装了 express 和 body-parser 模块),做一个小的计算并返回结果,更新一个 html 字段。我收到以下错误:位置 0 的 JSON 中出现意外的令牌 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));
});

静态/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;});
}

静态/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);
}

静态/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)

【问题讨论】:

  • 在 app.post("/num") 里面,你在执行 console.log(req.body) 时得到了什么?
  • 同样的错误:SyntaxError: Unexpected token 0 in JSON at position 0 at JSON.parse () at createStrictSyntaxError (/Users/Rob/Desktop/app2/node_modules/body-parser/ lib/types/json.js:158:10) 在解析时 (/Users/Rob/Desktop/app2/node_modules/body-parser/lib/types/json.js:83:15)
  • 表示请求中包含无效的 JSON。您可以从 DevTools 网络面板发布请求有效负载的屏幕截图吗?
  • 好像您没有传递有效的 JSON 数据,请查看我的回答。

标签: json node.js express xmlhttprequest body-parser


【解决方案1】:

您似乎没有根据请求传递 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;
};

【讨论】:

  • 这似乎行得通! (注意:将函数重命名为“validateJSON”以匹配调用)。答案在客户端的 html 中正确显示,但仍在日志中显示“位置 1 处 JSON 中的意外标记 o”
猜你喜欢
  • 2015-07-01
  • 1970-01-01
  • 2013-12-21
  • 2016-07-25
  • 1970-01-01
  • 2013-10-14
  • 2013-09-29
  • 1970-01-01
  • 2021-09-30
相关资源
最近更新 更多