Angular 7:对预检请求的响应未通过访问控制检查:请求中不存在“Access-Control-Allow-Origin”标头

Isa*_*ala 5 javascript amazon-web-services angular angular7

我必须使用 CURD 操作实现一个角度应用程序。API 已经托管在 AWS 中,它与 Postman 一起工作得很好。

但我的角度应用程序得到

CORS 政策已阻止在“ https://acp56df5alc.execute-api.us-east-1.amazonaws.com/ams/getmember 处访问 XMLHttpRequest来自源“ http://localhost:4200 ”:响应预检请求未通过访问控制检查:请求的资源上不存在“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;
            }));
    }
Run Code Online (Sandbox Code Playgroud)

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

ovi*_*cko 9

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

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

原始请求:

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

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

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


jcu*_*ers 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',
  ...
Run Code Online (Sandbox Code Playgroud)

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