0

嗨,我正在为后端和 Angular 5 应用程序作为客户端开发 django rest 框架。我需要在每个请求中向服务器发送 JWT 令牌和 Content-Type 如何在请求标头中设置“jsonwebtoken”和“content-type”? ?? 看起来 RequestOptions 和 Header 在 Angular 5 中已被弃用任何解决方案???

import {Injectable} from '@angular/core';
import {Headers, RequestOptions} from '@angular/http'
import {HttpClient} from "@angular/common/http";
import 'rxjs/add/operator/map'


@Injectable()
export class UserService {

  private options;
  constructor(private http: HttpClient) {
    const token = localStorage.getItem('theuser');

    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', 'Bearer' + ' ' + token)
    this.options = new RequestOptions({headers: headers});

    console.log(this.options)
  }


  userInfo() {
    return this.http.get<any>("http://localhost:8000/user-detail/",this.options)

  }

}
4

2 回答 2

1

您可以扩展 http 拦截器类。使用以下内容创建新的服务 token.interceptor.ts。

import { Injectable } from '@angular/core';

import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
declare var localStorage : any;

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor() {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let allowedUrls =( request.url.indexOf("dealer/signup") < 0 && request.url.indexOf("dealer/login") < 0 );   

    if(allowedUrls){

        let authToken = localStorage.getItem("dealertoken");
        request = request.clone({
            headers: request.headers.set('Authorization', 'Bearer '+ authToken)
            /* setHeaders: {
                Authorization: 'Bearer '+ authToken
            } */
        });
    }
    return next.handle(request);
  }
}

并将其导入 app.module.ts

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    }
  ],
于 2018-01-29T12:47:11.267 回答
0

您传递的第二个参数是选项。它包含headers属性。您可以将标题添加到此属性中。

不推荐使用怎么-从@angular/common/http.

如果需要为每个token添加JWT,最好使用HttpInterceptor

于 2018-01-29T12:43:02.767 回答