node.js请求数据事件未在CORS ajax调用上触发

时间:2015-04-08 18:52:06

标签: javascript jquery ajax json node.js

我正在尝试从jquery进程的ajax CORS调用中接收json。但是req.on('data' function(chunk) { })事件没有被调用。我在jquery过程中将json打印到屏幕上,它显示的是JSON。在类似的堆栈溢出问题中,该人在数据事件之前正在进行路由,这就是它无法正常工作的原因。或者该人正在发出没有正文的GET请求,并且不会调用数据事件。无论哪种方式,我都不确定为什么数据事件没有触发。

 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",
      })
    }
  };
});

1 个答案:

答案 0 :(得分:1)

OPTIONS请求与PUT请求是分开的,因此您的代码应如下所示:

if (req.url === '/') {
  if (req.method === "OPTIONS") {
    res.writeHead(204, "No Content", ...);
    res.end();
  } else if (req.method === 'PUT') {
    var requestBodyBuffer = [];
    req.on('data', ...);
    req.on('end', ...);
  }
}