簡體   English   中英

cors JSON輸入意外結束

[英]cors unexpected end of JSON input

end解析了json,但仍收到此錯誤。

'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);

從客戶端發送的數據:

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

我已成功收到json,但無法解析它。

更新:

我已經更新了代碼,以完整包含服務器代碼。

要完全清楚,請使用以下代碼:

....
}).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);
});

產生這個

描述

我們可以看到服務器代碼嗎?

我相信,這是一個(或多或少)您正在嘗試的端到端工作示例。

"use strict";
const http = require('http');

/********************
  Server Code
********************/
let data = {
    operation: 'shutdown',
    timeout: 120
};
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write(JSON.stringify(data));
    res.end();
});
server.listen(8888);

/********************
  Client Code
********************/
let options = {
    hostname: 'localhost',
    port: 8888,
    path: '/',
    method: 'POST',
    headers: {
        'Accept': 'application/json'
    }
};
let req = http.request(options, res => {
    let buffer = '';
    res.on('data', chunk => {
        buffer += chunk;
    });
    res.on('end', () => {
        let obj = JSON.parse(buffer);
        console.log(obj);
        // do whatever else with obj
    });
});
req.on('error', err => {
    console.error('Error with request:', err);
});
req.end(); // send the request.

事實證明,由於這是一個跨域(cors)請求,因此它試圖解析預檢請求中發送的數據。

我只需要添加一個if就可以了

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

成功

如果您有興趣進一步閱讀: HTTP訪問控制(CORS)

將標識符放在引號中。

{
    "operation": "shutdown",
    "timeout": 120
}

http://jsonlint.com/是有用的資源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM