Atu*_*han 5 httpclient ionic-framework angular
我一直在尝试向支持的API发送发布请求以发布一些数据。我已经尝试使用邮递员使用此API,并且可以正常工作,并且可以正确返回数据。但是,当我尝试通过离子角度应用程序执行相同操作时,它根本无法工作。我尝试了网络上可用的大多数方法,但是都没有成功。我正在使用Angular v6.0.8和Ionic框架v4.0.1构建此应用程序。该API要求请求正文中包含application / x-www-form-urlencoded数据(包括用户名,密码和grant_type)。我尝试使用旧版http和新的httpClient模块,但没有运气。到目前为止,我已经尝试使用URLSearchParams / JSONObject / HttpParams创建请求的正文。对于标头,我使用HttpHeaders()发送以Content-Type编码的application / x-www-form-urlencode。这些方法均无效。
有人能帮我一下吗?
PFB是到目前为止我尝试过的方法之一。
谢谢,阿图尔
import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable()
export class AuthService {
constructor(private http: HttpClient) {
}
signin(username: string, password: string){
const formData = new FormData();
formData.append('username', username);
formData.append('password', password);
formData.append('grant_type', 'password');
this.http.post(apiUrl,formData,
{
headers: new HttpHeaders({
'Content-Type':'application/x-www-form-urlencoded'
})
}
)
.subscribe(
(res) => {
console.log(res);
},
err => console.log(err)
);
}
}
Run Code Online (Sandbox Code Playgroud)
Avr*_*gil 13
我试图从端点获取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)
);
}
Run Code Online (Sandbox Code Playgroud)
如果出现cors错误,只需设置一个角度代理:
//proxy.conf.json
{
"/oauth": {
"target": "URL TO TOKEN ENDPOINT",
"changeOrigin": true,
"secure": false,
"logLevel": "debug",
"pathRewrite": {
"^/oauth": ""
}
}
}
Run Code Online (Sandbox Code Playgroud)
您无需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)
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16301 次 |
| 最近记录: |