标头未随HTTP请求一起发送

时间:2019-04-04 07:08:38

标签: angular angular-http angular-httpclient

我编写了一项服务,可以将GET和POST请求发送到我的API。我为标题编写了另一个函数。

我的服务文件如下:

import {HttpClient, HttpHeaders} from '@angular/common/http';
import {environment} from '../../environments/environment';
import {Injectable} from '@angular/core';

@Injectable()
export class HttpRequestsService {

  private apiUrl = environment.apiUrl;

  constructor(private http: HttpClient) {
  }

  private getHttpHeaders() {
    const token = sessionStorage.getItem('diagnostic_token');
    return new HttpHeaders({
      'Content-Type': 'application/json',
      Accepts: '*/*',
      Authorization: `Token ${token}`,
    });
  }

  public httpGet(urlEndpoint: string) {
    const options = {headers: this.getHttpHeaders()};
    return this.http.get(this.apiUrl + urlEndpoint, options);
  }

  public httpPost(urlEndpoint: string, body: {}) {
    return this.http.post(this.apiUrl + urlEndpoint, body, {headers: this.getHttpHeaders()});
  }
}

现在的问题是发送请求时标头为空。而且由于请求中不存在令牌头,因此响应中出现身份验证错误。

这是我的chrome请求

常规

Request URL: http://localhost:8000/user/me 
Request Method: OPTIONS
Status Code: 200 OK 
Remote Address: 127.0.0.1:8000
Referrer Policy: no-referrer-when-downgrade

响应标题

Access-Control-Allow-Headers: accept, accept-encoding, authorization,
content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with
Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT
Access-Control-Allow-Origin: * Access-Control-Max-Age: 86400
Content-Length: 0 Content-Type: text/html; charset=utf-8 Date: Thu, 04
Apr 2019 06:54:41 GMT Server: WSGIServer/0.2 CPython/3.7.3 Vary:
Origin X-Frame-Options: SAMEORIGIN

请求标头

Access-Control-Request-Headers: accepts,authorization,content-type Access-Control-Request-Method: GET
Origin: http://localhost:4200 Referer: http://localhost:4200/login
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86
Safari/537.36 x-ijt: 6ciqfq894dk1vb5nbp8o5e6u3a

0 个答案:

没有答案