Cors意外的JSONinput结束
我parsing我的JSON end
但我仍然收到此错误。
'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,但我无法parsing它。
更新:
我更新了代码以包含整个服务器代码。
要完全清楚,使用下面的代码:
.... }).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); });
产生这个
我们可以看到服务器代码吗?
我相信这里是一个工作的端到端的例子,或多或less是你正在尝试的。
"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.
事实certificate,由于这是一个交叉源(cors)请求,它试图分析在预先发送的请求中发送的数据。
我只是不得不添加一个if
要抓住这个
.... }).on('end', function() { if (request.method !== 'OPTIONS') { var data = JSON.parse(body); handleData(data); } });
如果您有兴趣进一步阅读: HTTP访问控制(CORS)