我一直在尝试向我的支持 API 发出发布请求以发布一些数据。我已经使用 postman 尝试了这个 API,它工作正常并且数据被正确返回。但是,当我尝试从我的 ionic-angular 应用程序执行相同操作时,它根本不起作用。网上的大部分方法我都试过了,但都无济于事。 我正在使用 Angular v6.0.8 和 Ionic 框架 v4.0.1 构建此应用程序。 API 需要请求正文中的 application/x-www-form-urlencoded 数据(包括用户名、密码和授权类型)。我尝试过同时使用旧版 http 和新的 httpClient 模块,但没有成功。到目前为止,我已经尝试使用 URLSearchParams/JSONObject/HttpParams 创建请求的主体。对于 header ,我使用 HttpHeaders() 将 application/x-www-form-urlencoded 作为 Content-Type 发送。这些方法都不起作用。
有人可以帮我吗?
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)
);
}
}
最佳答案
我试图从一个端点获取一个 oauth token ,我可以说很难找到一个有效的答案。
下面是我如何让它在 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 错误,只需设置一个 Angular 代理:
//proxy.conf.json
{
"/oauth": {
"target": "URL TO TOKEN ENDPOINT",
"changeOrigin": true,
"secure": false,
"logLevel": "debug",
"pathRewrite": {
"^/oauth": ""
}
}
}
关于带有 x-www-form-urlencoded 数据的 Angular 6 http post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51605542/