cors JSON输入意外结束 [英] cors unexpected end of JSON input

查看:129
本文介绍了cors JSON输入意外结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析end上的json,但仍收到此错误.

I am parsing my json on end but I am still receiving this error.

'use strict';
const http = require('http');
const tools = require('./tools.js');

const server = http.createServer(function(request, response) {
    console.log("received " + request.method + " request from " + request.headers.referer)

    var body = "";
    request.on('error', function(err) {
        console.log(err);
    }).on('data', function(chunk) {
        body += chunk;
    }).on('end', function() {
        console.log("body " + body);
        var data = JSON.parse(body); // trying to parse the json
        handleData(data);
    });

    tools.setHeaders(response);
    response.write('message for me');
    response.end();
});
server.listen(8569, "192.168.0.14");

console.log('Server running at 192.168.0.14 on port ' + 8569);

正在从客户端发送数据:

Data being sent from the client:

var data = JSON.stringify({
    operation: "shutdown",
    timeout: 120
});

我成功接收了json,但无法解析.

I successfully receive the json but I am unable to parse it.

更新:

我已经更新了代码,以完整包含服务器代码.

I've updated the code to include the server code in its entirety.

要完全清楚,请使用以下代码:

To be perfectly clear, using the following code:

....
}).on('end', function() {
        console.log("body " + body);
        var json = JSON.parse(body); // trying to parse the json
        handleData(json);
});

我明白了:

但是,这:

....
}).on('end', function() {
    console.log("body " + body);
    //var json = JSON.parse(body); // trying to parse the json
    //handleData(json);
});

产生了这个

推荐答案

事实证明,由于这是一个跨域(cors)请求,因此它试图解析预检请求中发送的数据.

It turns out that as this is a cross-origin(cors) request, it was trying to parse the data sent in the preflighted request.

我只需要添加一个if即可捕获

I simply had to add an if to catch this

....    
}).on('end', function() {
    if (request.method !== 'OPTIONS') {
        var data = JSON.parse(body);
        handleData(data);
    }
});

如果您有兴趣请进一步阅读: HTTP访问控制(CORS )

Further reading if you're interested: HTTP access control (CORS)

这篇关于cors JSON输入意外结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆