【问题标题】:Getting XMLHttpRequest while also receiving the response body在接收响应正文的同时获取 XMLHttpRequest
【发布时间】:2017-08-02 16:23:34
【问题描述】:

更新:虽然我在 AWS API Gateway api 上设置了 CORS,但我使用的是 Lambda 代理配置,这要求我将所需的标头放入 Lambda 处理程序中。

我想不出来这个。我收到 CORS 错误,同时获得响应正文(实际预期响应)。我正在使用 angular2/http。

XMLHttpRequest 无法加载 https://xxxxxx.execute-api.us-east-2.amazonaws.com/dev/search。不 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:4200” 访问。

知道这怎么可能吗??

代码(错误总是被捕获并打印出来,而我仍然得到适当的响应):

  public getNotes(searchString: string, authtoken: string): Observable<NotesResponse> {
    let headers = new Headers({'Content-Type': 'application/json'});
    headers.append('Authorization', authtoken);
    headers.append('search-key', searchString);

    let options = new RequestOptions({headers: headers});
    return this.http.post(this.notesUrl, null, options) // ...using post request
      .map((res:Response) => res.json()) // ...and calling .json() on the response to return data
      .catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if
  }

this.com.notesService.getNotes(this.com.searchQuery, result).subscribe(
  notes => {
    console.log("Notes: notes");
  },
  err => {
    // Log errors if any
    console.log("There was an error retrieving the notes: " + err);
  });

【问题讨论】:

  • 这根本不能回答我的问题。我得到了实际的响应 json,但同时我得到了 CORS 异常。如果这只是一个 CORS 问题,我将无法在资源上发帖。

标签: angular http xmlhttprequest cors observable


【解决方案1】:

浏览器获取响应并可以访问它,这就是它可以在 devtools 中显示它的原因。您无法从代码中获取它的原因是,浏览器不允许您的代码访问它——因为服务器没有发送 Access-Control-Allow-Origin 响应标头来告诉浏览器允许客户端 JavaScript 代码跨域访问它的响应。

CORS 不会阻止服务器将响应发送回浏览器。服务器无论如何都会发回响应,而浏览器无论如何都会接收它们。但仅仅因为浏览器收到了响应并不意味着浏览器会将其暴露给您的客户端代码。浏览器只有在包含 Access-Control-Allow-Origin 标头时才会公开对您的代码的跨域响应。

【讨论】:

  • 你是对的。尽管我在 AWS API Gateway api 上设置了 CORS,但我使用的是 Lambda 代理配置,这要求我将所需的标头放入 Lambda 处理程序中,因为 API Gateway 标头基本上被忽略了。你的帖子让我看起来更难了。谢谢! :)
猜你喜欢
  • 2019-09-28
  • 1970-01-01
  • 1970-01-01
  • 2011-12-24
  • 2011-07-02
  • 1970-01-01
  • 2020-08-11
  • 2011-11-09
  • 2018-05-01
相关资源
最近更新 更多