【问题标题】:node.js request data event not firing on CORS ajax callnode.js 请求数据事件未在 CORS ajax 调用上触发
【发布时间】: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


    【解决方案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', ...);
      }
    }
    

    【讨论】:

    • 我试过了,但 else if (req.method === 'PUT') 永远不会被称为 if (req.method === "OPTIONS") {
    • 没关系我忘记了res.end(),所以现在可以了,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多