Angular 6 - Instagram POST API 用于 Angular 中的身份验证显示 CORS 错误

Angular 6 - Instagram POST API for authentication in Angular shows CORS error

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

时根据 doc 首先调用 get URL 时得到 ?code=XXX

下一步,我必须调用 POST 方法来获取 IG 授权令牌和用户详细信息。 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 中工作正常

好吧,我不知道发生了什么,但是,它不是以 JSON 形式发送数据,而是需要以 POST 形式数据形式发送数据。所以,我这样做了:

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 数据。