作者:MrTkinG | 来源:互联网 | 2022-12-09 10:35
1> Avram Virgil..:
我试图从端点获取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": ""
}
}
}
2> Anuradha Gun..:
您无需JSON.stringify(formData)
仅将formData
用作方法的第二个参数http.post
。
创建的实例FormData
。然后附加您需要使用发送的值formData.append()
。
而httpHeaders
喜欢这个。
const httpOptiOns= {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})};
const formData = new FormData();
formData.append('username', username);
formData.append('password', password);
formData.append('grant_type', 'password');
this.http.post(apiUrl,formData,httpOptions)
.subscribe(
(res) => {
console.log(res);
},
err => console.log(err)
);