【问题标题】:Setting Headers for GET Request - Angular 2 Observable/Promise为 GET 请求设置标头 - Angular 2 Observable/Promise
【发布时间】:2017-04-12 23:58:52
【问题描述】:

当使用 HTTP GET 访问我的 Cloudant/NoSQL 数据库时,我目前收到 Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. 错误。

我知道设置 Access-Control-Allow-Origin: * 将允许来自 localhost 的 GET 请求,但是我没有看到 Angular 2 专门用于设置标头的文档。

async getData(): Promise<IPost[]> {
    return this._http.get(this._postUrl)
        .toPromise()
        .then(this.extractData)
        .catch(this.handleError);
}

IPost[] 是执行extractData() 后将返回的对象。

感谢您的帮助,感谢您的宝贵时间!

【问题讨论】:

  • 您需要在服务器上设置此标头,而不是在 Angular 应用程序中。
  • 找到了,隐藏在数据库的设置深处。谢谢!

标签: angular get promise http-headers observable


【解决方案1】:

当我想调用 REST API 时,我通常会使用它。 data 是您发送的请求对象。

 const HEADERS = new Headers({'Content-Type': 'application/json'});

     this.http.post(ENDPOINT, JSON.stringify(data), {headers: HEADERS})
          .map(this.extractData)
          .subscribe(
            payload => {
                           //do some operation or set values with payload
                        }
          );

这是用于邮寄电话的。如果您想使用 GET 调用,则不必在 angular 2 侧设置任何标题。只需要在后端允许对您的本地主机/特定机器的请求。

【讨论】:

    猜你喜欢
    • 2014-08-23
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    相关资源
    最近更新 更多