node web服务端跨域预请求未通过,求解!

菜鸟想用 node express 搭一个服务端,跨域问题一直没能解决。在请求JSON数据的时候,预请求始终无法通过权限控制,无法完成跨域过程,搞得我不知所措。

以下是前端请求代码:

    $.ajax({    
      type: "get",
      dataType: "json",
      url: "http://localhost:8080",
      processData: false,
      contentType: 'application/json',
      success: function(res)
      {
        console.log(res);
      }
    });

    let xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://localhost:8080', true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send();
    xhr.onreadystatechange = function()
    {
      console.log(xhr.responseText);
    }

jquery v2.1.4,两种方法都不行,同样的错误信息。

这是 express 4 的配置:

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:3000");
    res.header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept, X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
    res.header("Access-Control-Allow-Credentials", "true");
    res.header("Content-Type", "application/json;charset=utf-8");  
    // if(req.method == "OPTIONS") 
    //     res.send(200);/*让options请求快速返回*/
    // else  
    //     next();
});

这是chrome网络请求里的信息:

General

Request URL: http://localhost:8080/
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade

Response Header

Allow: GET,HEAD
Connection: keep-alive
Content-Length: 8
Content-Type: text/html; charset=utf-8
Date: Mon, 16 Apr 2018 04:23:20 GMT
ETag: W/"8-ZRAf8oNBS3Bjb/SU2GYZCmbtmXg"
X-Powered-By: Express

报头中没有允许 OPTIONS 请求,可在 express 中明明设置了。

这是报错信息:

Failed to load http://localhost:8080/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

求解惑,谢谢!

阅读 2.2k
1 个回答

使用cors模块解决试试

var cors = require('cors') ;
app.use(cors(
  {
    "origin": "*",
    "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  }
))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题