我试图从端点获取 oauth 令牌,我可以说很难找到有效的答案。
下面是我如何使它在 Angular 7 中工作,但这也适用于 Angular 6
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
login(user: string, password: string) {
const params = new HttpParams({
fromObject: {
grant_type: 'password',
username: user,
password: password,
scope: 'if no scope just delete this line',
}
});
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa('yourClientId' + ':' + 'yourClientSecret')
})
};
this.http.post('/oauth', params, httpOptions)
.subscribe(
(res: any) => {
console.log(res);
sessionStorage.setItem('access_token', res.access_token);
sessionStorage.setItem('refresh_token', res.refresh_token);
},
err => console.log(err)
);
}
如果出现 cors 错误,只需设置一个角度代理:
//proxy.conf.json
{
"/oauth": {
"target": "URL TO TOKEN ENDPOINT",
"changeOrigin": true,
"secure": false,
"logLevel": "debug",
"pathRewrite": {
"^/oauth": ""
}
}
}