【发布时间】:2015-04-08 18:52:06
【问题描述】:
我正在尝试从 jquery 进程的 ajax CORS 调用接收 json。但是没有调用req.on('data' function(chunk) { }) 事件。我在 jquery 过程中将 json 打印到屏幕上,它显示的是 JSON。在类似的堆栈溢出问题中,该人在数据事件之前进行路由,这就是它不起作用的原因。或者该人正在发出没有正文且不会调用数据事件的 GET 请求。无论哪种方式,我都不确定为什么 data 事件没有触发。
const https = require('https');
var options = {
key: fs.readFileSync('domain.key'),
cert: fs.readFileSync('domain.crt')
};
https.createServer(options, function(req, res) {
var origin = (req.headers.origin || "*");
if(req.method === "OPTIONS" && req.url === '/') {
res.writeHead(204, "No Content", {
"access-control-allow-origin": origin,
"access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
"access-control-allow-headers": "content-type, accept",
"access-control-max-age": 10,
"content-length": 0
});
var requestBodyBuffer = [];
req.on('data', function(chunk) {
requestBodyBuffer.push(chunk);
console.log('here'); //Not printing.
})
req.on('end', function() {
var requestBody = requestBodyBuffer.join("");
console.log(requestBody); // Empty
var obj = JSON.parse(requestBody); // crashes here
if(obj.hasOwnProperty('username') && obj.hasOwnProperty('password')) {
console.log(obj.username);
console.log(obj.password);
}
})
}
}).listen(443);
这里是 jquery ajax 调用。
$(document).ready(function() {
$('#loginbtn').click(clickLogin);
function clickLogin() {
var username = $('#username').val();
var password = $('#password').val();
if(password == '' || username == '') {
$(".out").html("Empty username or password");
} else {
$.ajax({
type: "PUT",
url: "https://localhost/",
contentType: "application/json",
data: JSON.stringify({
username: username,
password: password
}),
dataType: "text",
})
}
};
});
【问题讨论】:
标签: javascript jquery ajax json node.js