Angular不发送请求标题值



我正在使用DJANGO REST框架作为后端,并试图在请求标头中使用令牌进行Angular中的请求,但Angular并未发送任何标头值。我尝试了所有添加标头的方法

test(){
    //var headers = new HttpHeaders();
     //headers.append('Authorization',':Token '+ token);
    let token='Token '+'d7dd1e453bae5086e33243b9adca5b63d2d927fb8';
    const httpOptions = {
      headers: new HttpHeaders({
        'Authorization':'Token d7dd1e453bae5086e33243b9adca5b63d2d927fb8',
        'Content-Type': 'application/json', 
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers':'X-Requested-With'
      })
    };
    console.log(token);
    this.http.get('http://localhost:8003/hello/', httpOptions).subscribe(
      response=>{console.log(response);}
    );
  }

访问控制标头: 访问控制者 - 允许头,访问控制 - 允许孔,授权,内容类型 访问控制 - 重试方法:get dnt:1起源: http://localhost:4001参考器:http://localhost:4001/

我在最近的项目中遇到了相同的问题,通过设置这样的标题来解决它:

let headers = new HttpHeaders().set('Authorization', 'Token ...')
                               .append('Content-Type', 'application/json')
                               .append('Access-Control-Allow-Origin', '*')
                               .append('Access-Control-Allow-Headers', 'X-Requested-With');
 // now either:
 const httpOptions = { headers: headers };
 this.http.get('http://localhost:8003/hello/', httpOptions);
 // or
 this.http.get('http://localhost:8003/hello/', { headers: headers });

问候。

最新更新