我正在向服务器发送一个获取请求,它需要一个 JWT token 来进行身份验证。然而,Ionic 坚持在没有请求的情况下执行预 eclipse 刻请求并崩溃。 (还有什么方法可以捕获非 200 响应?服务器提供了很多响应(例如 403 {message: Account Invalid}))
代码
auth.ts
import { Headers, RequestOptions } from '@angular/http'
import 'rxjs/add/operator/toPromise';
...
export const getToken = function(http){
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', 'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU4Yzg1MmI1YmQ1NjE1MGJkMDAxZWEzNyIsImlhdCI6MTQ4OTY3ODE0NywiZXhwIjoxNDg5NjgxNzQ3fQ.zUWvBnHXbgW20bE65tKe3icFWYW6WKIK6STAe0w7wC4');
let options = new RequestOptions({headers: headers});
http.get('//localhost:3000/auth/users', {headers: options})
.toPromise()
.then(res => resolve(res))
.catch(err => console.log(err));
});
}
Chrome 控制台:
Response for preflight has invalid HTTP status code 401
服务器看到:(我注销了请求,没有标题或正文)
OPTIONS /auth/users 401 25.613 ms - -
最佳答案
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Toast, Device } from 'ionic-native';
import { Http, Headers } from '@angular/http';
let headers = new Headers();
headers.append('Token', this.Token);
headers.append('id', this.ID);
this.http.get(this.apiUrl + this.yourUrl, { headers: headers })
.map(res => res.json())
.subscribe(
data => {
console.log(data);
if (data.code == 200) { // this is where u r handling 200 responses
if (data.result.length > 0) {
for (let i = 0; i < data.result.length; i++) {
var userData = {
username: data.result[i].username,
firstName: data.result[i].firstName,
lastName: data.result[i].lastName,
}
console.log(JSON.stringify(userData));
this.Results.push(userData);
}
}
}
else { // here non 200 responses
console.log(data.message);
}
this.user= this.Results;
console.log(this.user);
},
err => {
console.log("ERROR!: ", err);
});
这样你将能够处理来自后端的所有响应
希望对你有用
关于angularjs - 带有授权 header 的 Ionic http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42839702/