angular - 如何在 Ionic 3 中使用 httpclient 解析 REST API 失败消息
问题描述
Web 服务返回以下 json 作为响应,状态码为 403。
{
"status": "failure",
"message": "Unauthorized request or the token is invalid"
}
如何在 ionic 3 中使用 httpClient 捕获状态和消息。
这是我的代码:
apiHttpOptions = {
headers : new HttpHeaders(),
params: new HttpParams(),
observe: 'response' as 'response',
};
//认证函数
public authenticate(){
let postData = new FormData();
postData.append("username", this.username);
postData.append("password", this.password);
this.authResponse = this.http
.post(this.baseUrl + "authenticate", postData, this.apiHttpOptions)
return new Observable(observer =>{
this.authResponse.subscribe((response) => {
console.log("======Authentication======");
let data = response.body;
console.log(data);
this.authToken = data["_token"];
this.storage.set('token',this.authToken);
observer.next(data);
}, err => {
console.log("======Auth Error =========");
// console.log(err);
observer.error(err);
})
})
}
解决方案
您可以在选项属性中使用 'observe' : 'response'。
const request = {
params: null,
body: null,
observe: 'response',
headers: ...,
};
HTTP 调用:
return this._http
.request<modelresponse>(method, url, request);
推荐阅读
- django - 如何从模板引用 django 视图中的设置对象?
- java - 为什么 `+ 1` 在 Java 中是一个有效的表达式?
- html - 使用 vuejs 根据各自的主页显示隐藏标题
- ionic3 - cordova-plugin-datecs-printer 无法打印图像
- javascript - 使用 CSP 的 nonce 策略响应 *.js.erb
- c# - 在 Xamarin 项目上运行 SonarScannerMSBuild 时出错
- sapui5 - 如何获取图像 SAPUI5 的尺寸?
- javascript - 从html读取文件到jquery,然后上传到ajax
- php - 快书支付整合问题
- flutter - 在 Flutter 的 TextFormField 中显示/隐藏密码