【问题标题】:Cross domain api call with post request in angular 2跨域 api 调用与角度 2 中的 post 请求
【发布时间】:2017-03-31 16:41:55
【问题描述】:
return this.http.post(this._InstUrl, body, options)
                               .map((res: Response) => {res.json() })
                               .subscribe(
                                        (data) => {
                                            console.log(this.Result);
                                        },
                                        (error) => {
                                             console.log(error);
                                        });

当我执行上面的代码时,它没有为我工作并显示下面提到的错误。

对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:55139' 不允许访问。响应的 HTTP 状态代码为 405。

谁能帮我解决这个问题?

【问题讨论】:

标签: angular instagram-api


【解决方案1】:

此处是 Angular 2 中跨域发布请求的示例

 this._InstUrl = 'https://api.instagram.com/v1/media/' + listOfMedia[0].id + '/likes?access_token=' + this.hdnaccess_token;
            let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' });
            var requestoptions = new RequestOptions({
                method: RequestMethod.Post,
                url: this._InstUrl,
                headers: headers,
            })

            return this.http.request(new Request(requestoptions))
                .map((res) => {
                    debugger;
                    if (res) {
                        //return { status: res.status, json: res.json() }
                    }
                })
                .subscribe(
                (data) => {
                    //if (this.Result.length == 0) { this.NoData = true; }
                    debugger; console.log(this.Result);
                },
                (error) => {
                    debugger; console.log(error);
                });

【讨论】:

  • 虽然这可能已经解决了您的问题,但它与 instagram API 有关,而不是一般的 CORS 问题。似乎 intagram API 不允许对任何不属于 Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' 的请求进行 CORS
  • 问题不在客户端,因为服务器必须为 cors 请求设置必要的标头。而且你的代码看起来不像是 jsonp 请求,这将是一个可能的解决方案
猜你喜欢
  • 1970-01-01
  • 2012-04-15
  • 2012-01-04
  • 2011-08-19
  • 2017-02-06
  • 2016-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多