首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有授权头的离子http请求

带有授权头的离子http请求
EN

Stack Overflow用户
提问于 2017-03-16 16:29:10
回答 2查看 15.1K关注 0票数 1

我向服务器发送一个get请求,它需要一个JWT令牌来进行身份验证。然而,Ionic坚持做一个预蚀刻请求,没有一个和崩溃。(此外,是否有任何方法来捕捉非200条回应?服务器提供了很多这些信息(例如403 {message: Account 403})

auth.ts

代码语言:javascript
复制
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控制台:

代码语言:javascript
复制
Response for preflight has invalid HTTP status code 401

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

代码语言:javascript
复制
OPTIONS /auth/users 401 25.613 ms - -
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-16 17:31:41

代码语言:javascript
复制
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);
        });

这样,您将能够处理来自后端的所有响应。

我希望这对你有用

票数 8
EN

Stack Overflow用户

发布于 2017-03-16 17:46:19

任何有这个问题的人。devanshsadhotra的回答很棒,但我解决这个问题的方法如下:

ionic.config.json (在这里添加所有相关路线)

代码语言:javascript
复制
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://localhost:3000/api"
    },
    {
      "path": "/auth",
      "proxyUrl": "http://localhost:3000/auth"
    }
  ]

您的网络文件(本例中为auth.js)

代码语言:javascript
复制
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...
    });
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42839702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档