首页 文章

Angular 2请求的资源上没有'Access-Control-Allow-Origin'标头[重复]

提问于
浏览
1

这个问题在这里已有答案:

我收到这个错误:

XMLHttpRequest无法加载API_URL . 请求的资源上不存在“Access-Control-Allow-Origin”标头 . 因此不允许来源'http:// localhost:4200'访问 .

从localhost调用远程API时 . 我无法访问API服务器,所以我不能在服务器端允许CORS . 以下是我从Angular服务调用API的方法:

this.http.get(url)
         .map(response  => response.json())
         .subscribe(data => this.myData.push(data));

之后我想使用成员 myData . 在查看chrome 's dev tools, I see a 200 message in the networks tab. It also shows the correct JSON Response, but I get the above error in the console and can'时使用数据 .

我一直在寻找如何解决这个问题 . 但是,修改浏览器选项和服务器设置不是一种选择 . 如果可能的话,我也想避免使用代理服务器 . 这也是我第一次使用Angular 2,所以我对事情的运作方式没有扎实的理解;所以我可能会以完全不同的方式提出请求 .

我还尝试将设置 Access-Control-Allow-Origin 添加到我的 Headers 中,如下所示:

let headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin');
headers.append('Access-Control-Allow-Origin', this.serverName);
this.http.get(url , {headers: headers})
    .map(response  => response.json())
    .subscribe(data => this.myData.push(data));

但是这导致了这个错误:

对预检请求的响应未通过访问控制检查:请求的资源上没有“Access-Control-Allow-Origin”标头

这次回复是空的 . 查看请求标头我没有看到 Access-Control-Allow-HeadersAccess-Control-Allow-Origin 设置 .append 调用的值 . 我正确设置这些 Headers 选项吗?

使用jsonp而不是http也没有用,因为标头上的应用程序类型设置为json:

拒绝从API_URL执行脚本,因为其MIME类型('application / json')不可执行,并且启用了严格的MIME类型检查 .

如果你在细节上解释修复,我会很感激,因为我无法在网上找到任何解决方案,也许我错过了一些重要的假设或必须知道 .

2 回答

  • 2

    Access-Control-Allow-Origin是 response header ,而不是 request header 您需要修复后端的权限(我使用nodejs) . 所以您必须创建包含所有必要权限的cors.js文件 .

    function crosPermission(){
      this.permission=function(req,res,next){
        res.header('Access-Control-Allow-Origin','*');
        res.header('Access-Control-Allow-Headers','Content-Type');
        res.header('Access-Control-Allow-Methods','GET','POST','PUT','DELETE','OPTIONS');
        next();
      }
    }
    
    module.exports= new crosPermission();
    

    next step 您需要在app.js中添加一些行

    var cors=require('./cors');
    app.use(cors.permission)
    
  • 1

    这是因为浏览器的安全功能强制执行相同的来源 . 见维基百科:https://en.wikipedia.org/wiki/Same-origin_policy

    所以它与Angular无关 . 您提到的代理服务器是解决问题的一种方法 . 但是你无法阻止浏览器执行这条规则,也不应该尝试 .

相关问题