【问题标题】:Angular 6 - Instagram POST API for authentication in Angular shows CORS errorAngular 6 - Angular 中用于身份验证的 Instagram POST API 显示 CORS 错误
【发布时间】:2018-11-19 06:55:44
【问题描述】:

我搜索了各种有关解决 CORS 错误的网站,但没有找到任何可行的解决方案。 因此,在我的一个项目中,我启用了 Instagram 身份验证。我在调用doc 时调用https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code 时调用第一个获取URL 时得到 ?code=XXX。

下一步,我将调用 POST 方法来获取 IG auth-token 和用户详细信息。 https://api.instagram.com/oauth/access_token 需要的数据。但是调用这个 API 会显示 CORS 错误:

我的代码(使用 Angular HTTPClient 模块):

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Access-Control-Allow-Origin':'*',
    'Content-Type': 'application/json'
  })
};

@Injectable({
  providedIn: 'root'
})
export class IgauthService {

  constructor(private http: HttpClient) { }

  instagramGetToken (igcode) {
    let data = {
      client_id: 'XXX',
      client_secret: 'XXX',
      grant_type: 'authorization_code',
      redirect_uri: 'http://localhost:4200/login',
      code: igcode
    }
    try {
      return this.http.post('http://api.instagram.com/oauth/access_token', data, httpOptions);
    }
    catch (err) {
      console.error(err);
      return err;
    };
  }
}

注意:这在 Postman 中运行良好

【问题讨论】:

  • 您是否添加了您的来源,您在哪里注册了您的应用程序。

标签: angular typescript authentication angular6 instagram


【解决方案1】:

嗯,我不知道发生了什么,但是,它需要将数据作为表单数据发送,而不是作为 JSON 发送数据。所以,我这样做了:

const body = new HttpParams()
    .set('client_id', 'XXX')
    .set('client_secret', 'XXX')
    .set('grant_type', 'authorization_code')
    .set('redirect_uri', `${location.protocol}//${location.hostname + (location.port ? ':' + location.port : '')}/`)
    .set('code', igcode)

    return this.http.post('https://api.instagram.com/oauth/access_token',
    body.toString(),
    {
        headers: new HttpHeaders()
        .set('Content-Type', 'application/x-www-form-urlencoded')
    }
    );

这很好用。仍然好奇为什么它不适用于 JSON 数据。

【讨论】:

    猜你喜欢
    • 2019-03-15
    • 1970-01-01
    • 2018-06-27
    • 2017-04-11
    • 2019-03-23
    • 2016-02-21
    • 2018-11-22
    • 2016-02-04
    • 2013-08-02
    相关资源
    最近更新 更多