具有授权标头的离子http请求 [英] Ionic http requests with authorization headers

查看:104
本文介绍了具有授权标头的离子http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向服务器发送get请求,它需要JWT令牌进行身份验证。然而,Ionic坚持要求在没有一个的情况下进行pref-etch请求并且崩溃。 (也有没有办法捕获非200个响应?服务器提供了很多这些(例如403 {消息:帐户无效}))

I am sending a get request to the server and it requires a JWT token to authenticate. However Ionic insists on doing a pref-etch request without one and crashing. (Also is there any way to capture non 200 responses? the server gives a lot of those (e.g. 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控制台:

Chrome console:

Response for preflight has invalid HTTP status code 401

服务器看到:(我注销了请求,没有标题或正文)

Server sees: (I logged out the request and there are no headers or body)

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);
        });

这样你就可以处理来自后端的所有回复

我希望这对你有用

这篇关于具有授权标头的离子http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆