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

发布于 2022-09-06 23:39:53 字数 2061 浏览 8 评论 0

菜鸟想用 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.

求解惑,谢谢!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

独留℉清风醉 2022-09-13 23:39:53

使用cors模块解决试试

var cors = require('cors') ;
app.use(cors(
  {
    "origin": "*",
    "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  }
))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文