【问题标题】:Access to XMLHttpRequest at 'http://localhost:1111/...' from origin 'http://localhost:4200' has been blocked by CORS policy:从源“http://localhost:4200”访问“http://localhost:1111/...”的 XMLHttpRequest 已被 CORS 策略阻止:
【发布时间】:2019-10-31 21:09:37
【问题描述】:

跨源未发生,被 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:4200”对“http://localhost:1111/api/v1/employees/create”处的 XMLHttpRequest 的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。 core.js:15724 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:1111/api/v1/employees/create", ok: false, ...}

谢谢

【问题讨论】:

  • cors 问题无法从客户端应用程序修复。我可以看到您正在使用代理,但它没有正确设置。

标签: angular cors angular7


【解决方案1】:

你可以试试这个

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 上工作时,您需要安装插件。

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

火狐

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

谢谢

【讨论】:

猜你喜欢
  • 2020-01-26
  • 2020-07-09
  • 1970-01-01
  • 2019-11-17
  • 1970-01-01
  • 2020-10-12
  • 2023-03-27
  • 2021-12-26
  • 2020-02-11
相关资源
最近更新 更多