2017-03-16 64 views
0

我向服务器发送获取请求,它需要一个JWT令牌进行身份验证。然而,Ionic坚持要做一个没有问题并且崩溃的pref-etch请求。 (?另外有没有什么办法来捕捉非200个响应服务器对很多这些的(如403 {消息:帐户无效}))带有授权标头的离子http请求

代码

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 - - 
+0

仅将http.get的使用更新为/ auth/users并更新ionic.project文件的代理设置 –

回答

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

这样ü将能够从后端

处理所有的回答,我希望这对你的作品

+0

非常感谢。我已经以不同的方式解决了它,但非常感谢你! 你能解释一下这个全局的东西吗? –

+0

欢迎@MHornbacher – devanshsadhotra

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