带有授权标头的离子 http 请求
Posted
技术标签:
【中文标题】带有授权标头的离子 http 请求【英文标题】:Ionic http requests with authorization headers 【发布时间】:2017-08-07 23:01:28 【问题描述】:我正在向服务器发送一个 get 请求,它需要一个 JWT 令牌来进行身份验证。然而,Ionic 坚持不做一个预蚀刻请求而导致崩溃。 (还有什么方法可以捕获非 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 - -
【问题讨论】:
仅将 http.get 的使用更新到 /auth/users 并更新 ionic.project 文件以进行代理设置 【参考方案1】: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);
);
这样你就可以处理来自后端的所有响应
我希望这对你有用
【讨论】:
非常感谢。我已经用不同的方式解决了,但非常感谢!你能解释一下 this.global 的事情吗? 欢迎您@MHornbacher @devanshsadhotra : 我用的是 laravel 5,你能解释一下服务器端吗? 你错过了这个:import 'rxjs/add/operator/map';
for .map()
函数【参考方案2】:
致遇到此问题的其他人。 devanshsadhotra 的回答很好,但这是我解决这个问题的方法:
ionic.config.json(在此处添加所有相关路由)
"proxies": [
"path": "/api",
"proxyUrl": "http://localhost:3000/api"
,
"path": "/auth",
"proxyUrl": "http://localhost:3000/auth"
]
您的网络文件(在本例中为 auth.js)
import Headers from '@angular/http' //Headers need to be in this object type
import 'rxjs/add/operator/toPromise'; //turns observable into promise
export const getToken = function(http) //passing in the Http handler to the function for no good reason. but it works
return new Promise((resolve, reject) => //return a promise to the calling function so it can handle the response
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', 'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU4Yzg1MmI1YmQ1NjE1MGJkMDAxZWEzNyIsImlhdCI6MTQ4OTY4MjY2MywiZXhwIjoxNDg5Njg2MjYzfQ.tW8nT5xYKTqW9wWG3thdwf7OX8g3DrdccM4aYkOmp8w');
http.get('/auth/users', headers: headers) //for post, put and delete put the body before the headers
.toPromise() //SANITY!!!
.then(res => resolve(res)) //Things went well....
.catch(err => console.log(err)); //Things did not...
);
【讨论】:
以上是关于带有授权标头的离子 http 请求的主要内容,如果未能解决你的问题,请参考以下文章