【问题标题】:Angular 7 : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requestedAngular 7:对预检请求的响应未通过访问控制检查:请求中不存在“Access-Control-Allow-Origin”标头
【发布时间】:2019-09-07 23:56:01
【问题描述】:

我必须使用 CURD 操作来实现 Angular 应用程序。 API 已经托管在 AWS 中,可以与 Postman 一起正常工作。

但我的 Angular 应用程序越来越

从源“http://localhost:4200”访问位于“https://acp56df5alc.execute-api.us-east-”的 XMLHttpRequest1.amazonaws.com/ams/getmember' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我的代码如下,

http_GET(actionUrl: string): Observable<any> {
        const httpOptions = {
            headers: new HttpHeaders({
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Credentials': 'true',
                'Access-Control-Allow-Headers': 'Content-Type',
                'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE',
                'key': 'x-api-key',
                'value': 'NNctr6Tjrw9794gFXf3fi6zWBZ78j6Gv3UCb3y0x',

            })
        };
        return this.http.get<any>(this.baseUrl + actionUrl, httpOptions).pipe(
            (response => {
                return response;
            }));
    }

我已经努力解决这个问题。但是需要一些帮助

【问题讨论】:

  • 我实际上只是收到了这个确切的错误消息(除了粗略的域),并且应用程序之前运行过,所以知道它不应该是一个真正的 CORS 问题,结果我有重命名服务器上的目录,但未重命名 web.config 文件中的目录。可能值得一看,看看您是否还有其他可能导致此误报错误消息的失败。

标签: javascript angular amazon-web-services angular7


【解决方案1】:

我遇到了同样的cors 问题,并尝试了所有设置Access-Control-Allow-Origin * 的建议方法,但均未成功。
后来发现两个问题:

  1. 我通过POST 发送的data format 请求格式不正确。
  2. 服务器无法处理从发布请求接收到的空参数。

原始请求:

return this.http.post(API_URL + 'customer/login',
  {email: email, password: password},{ headers: headers}
)

在我使用 JSON.stringify() 包装帖子数据后工作

return this.http.post(API_URL + 'customer/login',
      JSON.stringify({email: email, password: password}),{ headers: headers}
    )

【讨论】:

    【解决方案2】:

    所有/大多数这些标头都需要在服务器端定义(无论在 AWS 上托管 API 的什么)...而不是客户端。

     headers: new HttpHeaders({
                    'Content-Type': 'application/json',
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Credentials': 'true',
                    'Access-Control-Allow-Headers': 'Content-Type',
                    'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE',
                    'key': 'x-api-key',
                    'value': 'NNctr6Tjrw9794gFXf3fi6zWBZ78j6Gv3UCb3y0x',
      ...
    

    邮递员工作的最可能原因是它直接发送 GET 请求。您发送的是一个复杂的请求,称为“飞行前”,它会导致在实际 GET 之前发送“选项”请求。这是远程端不允许的。

    【讨论】:

    • 这些属性应该在哪里定义?
    猜你喜欢
    • 2018-08-04
    • 2020-12-07
    • 2019-02-02
    • 1970-01-01
    • 2018-10-12
    • 2016-02-23
    • 2018-05-06
    • 1970-01-01
    • 2017-11-11
    相关资源
    最近更新 更多