具有授权标头的离子http请求

时间:2017-03-16 16:29:10

标签: angularjs typescript ionic2

我正在向服务器发送get请求,它需要JWT令牌进行身份验证。然而,Ionic坚持要做一个pref-etch请求,没有一个并且崩溃。 (还有没有办法捕获非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 - -

2 个答案:

答案 0 :(得分:6)

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

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

我希望这对你有用

答案 1 :(得分:1)

对任何有这个问题的人。 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...
    });
}