typescript 带有授权标头的 Ionic http 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42839702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:21:27  来源:igfitidea点击:

Ionic http requests with authorization headers

angularjstypescriptionic2

提问by M Hornbacher

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

我正在向服务器发送一个 get 请求,它需要一个 JWT 令牌来进行身份验证。然而,Ionic 坚持不执行预蚀刻请求并导致崩溃。(还有什么方法可以捕获非 200 响应?服务器提供了很多响应(例如 403 {message: Account Invalid}))

Code

代码

auth.ts

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

回答by Devansh sadhotra

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 way u will be able to handle all responses from backend

这样你就可以处理来自后端的所有响应

I hope this works for you

我希望这对你有用

回答by M Hornbacher

To anyone else having this issue. devanshsadhotra's answer is great but here is the way I solved this issue:

对于遇到此问题的任何其他人。devanshsadhotra 的回答很好,但这是我解决这个问题的方法:

ionic.config.json (add all the relevant routes here)

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

  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://localhost:3000/api"
    },
    {
      "path": "/auth",
      "proxyUrl": "http://localhost:3000/auth"
    }
  ]

Your networking file (auth.js in this case)

您的网络文件(在本例中为 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...
    });
}