能否在Angular 8中调用yahoo contact API?

问题描述 投票:0回答:1

在Angular应用中,我需要请求yahoo contact API:首先我想知道是否可以从客户端请求?

ngOnInit(): void {
      this.route.queryParams.subscribe(q => {

      const body = {
        client_id: this.yahooObj.clientId,
        client_secret: this.yahooObj.clientSecret,
        redirect_uri: this.yahooObj.redirect,
        code: q.code,
        grant_type: 'authorization_code'
      }
      this.http.post<any>('https://api.login.yahoo.com/oauth2/get_token',
        body, {headers: new HttpHeaders({
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'Authorization': 'Basic' + btoa(`${this.yahooObj.clientId}:${this.yahooObj.clientSecret}`)
          })})
        .subscribe(data => {
          console.log('return data service', data);
        }, (err: HttpErrorResponse) => {
          console.log('Error', err);
        });
  });
}

 yahooAuth() {
    window.open(`https://api.login.yahoo.com/oauth2/request_auth?client_id=${this.yahooObj.clientId}&response_type=code&redirect_uri=${this.yahooObj.redirect}`);
  }

从yahoo认证页面重定向和贝克代码工作正常,但http.post请求回到下面的Errors about CORS policy,因为在postman工作正常。

访问XMLHttpRequest在'https:/api.login.yahoo.comoauth2get_token。'从源头开始'http:/localhost:3201'已被CORS政策阻止。对飞行前请求的响应没有通过访问控制检查。No 'Access-Control-Allow-Origin' header is present on the requested resource.

因为在postman中没有问题,而在浏览器中却出现了CORS策略错误,我需要确定有什么方法可以在客户端调用这个API?

javascript angular yahoo-api
1个回答
0
投票

你的代码中少了一个空格 Basic 和令牌。请尝试以下步骤

'Authorization': 'Basic ' + btoa(`${this.yahooObj.clientId}:${this.yahooObj.clientSecret}`)

请注意字后的空格 Basic.

关于CORS的问题,你可以在前端设置一个代理来重定向请求。


0
投票

你可以在后端服务器写雅虎API调用,然后从angular客户端调用API,这就是所谓的代理。这样可以解决CORS问题。

© www.soinside.com 2019 - 2024. All rights reserved.