是否可以在 Angular 8 中调用雅虎联系人 API



在角度应用程序中,我需要请求雅虎联系人API: 首先,我想知道是否可以从客户那里请求? 我在 Angular 中的代码是:

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}`);
}

从雅虎身份验证页面重定向和贝克代码工作正常,但 http.post 请求返回有关 CORS 策略的错误下方,因为在邮递员中工作正常。

CORS 策略已阻止从源"http://localhost:3201"访问"https://api.login.yahoo.com/oauth2/get_token"处的 XMLHttpRequest:对预检请求的响应未通过访问控制检查:请求的资源上不存在"访问控制-允许源"标头。

由于在邮递员中还可以,并且在浏览器中有此 CORS 策略错误,我需要确保有什么方法可以在客户端中调用此 API?

Basic和令牌之间缺少空格。尝试以下操作

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

请注意单词Basic后面的空格。

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

您可以在后端服务器中编写Yahoo API调用,并从角度客户端调用API,这就是所谓的代理。这可以解决CORS问题。

最新更新