通过CORS策略已阻止从来源“ http:// localhost:4200”访问“ http:// localhost:1111 / ...”处的XMLHttpRequest:

时间:2019-06-18 09:03:52

标签: angular cors angular7

由于CORS政策的限制,没有发生过跨境交易。

我在Windows系统上。

-.service.ts文件中:

 makeHeaders() {
    const headers = new HttpHeaders({
      'content':"application/json",
      'Content-Type': 'application/x-www-form-urlencoded',
      // 'Access-Control-Allow-Credentials': 'true',
      'Access-Control-Allow-Origin': 'http://localhost:4200',
      'Access-Control-Allow-Methods': 'OPTIONS, GET, POST',
      'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Access-Control-Allow-Origin, Authorization, X-Requested-With'
      })
    return headers;
  }

proxy.conf.json文件中:

"target": "http://localhost:1111"

我在浏览器控制台中遇到此错误:

  

从原点“ http://localhost:1111/api/v1/employees/create”到“ http://localhost:4200”处对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否'Access-Control-Allow-来源的标头出现在请求的资源上。   core.js:15724错误HttpErrorResponse {headers:HttpHeaders,status:0,statusText:“ Unknown Error”,url:“ http://localhost:1111/api/v1/employees/create”,ok:false,...}

谢谢

1 个答案:

答案 0 :(得分:0)

您可以尝试

app.options("/*", function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    res.sendStatus(200);
});

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    next();
});

在localhost上工作时,需要安装插件。

  

Chrome

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

  

FireFox

https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/

谢谢