【问题标题】:Unable to get User angular 2(Authentication credentials were not provided)无法获取用户角度 2(未提供身份验证凭据)
【发布时间】:2018-03-16 09:56:32
【问题描述】:

我正在尝试通过以下方式从我的角度服务获取请求来获取用户信息。

import { Injectable } from '@angular/core';
import {homeUrls} from "../../../utils/urls";
import {Http, RequestOptions, Response} from '@angular/http';
import { Headers } from '@angular/http';
@Injectable()
export class AdsService {
  private headers = new Headers({'Content-Type': 'application/json'});
  private token: string;
  constructor(private http: Http) {
    this.token = localStorage.getItem('token');
    console.log("token is " , this.token);
    this.headers.set('Authorization', 'Token ' + this.token );
    console.log("header is");
    console.log(this.headers);
    this.getMe();
  }

  getMe(): Promise<any> {
      return this.http.get(homeUrls.User, {headers: this.headers})
        .toPromise()
        .then(res=> {
          console.log("user is");
          console.log(res.json());
        })

  }

但我收到以下错误

无法加载 http://127.0.0.1:8000/users/account/me/:预检响应包含无效的 HTTP 状态代码 401。

当我签入网络选项卡时,它显示“未提供身份验证凭据”,尽管我已经设置了授权标头,因为它可以在我的服务的构造函数中看到。知道这里有什么问题吗?

【问题讨论】:

    标签: angular angular2-services angular4-httpclient


    【解决方案1】:

    Headers 是一个不可变的对象。 set 和 append 方法不修改 Headers 对象,它们返回一个新对象。

    另外,您可能希望使用追加而不是设置。

    【讨论】:

    • 我也使用了 append,但同样的回复,“未提供身份验证凭据”
    • 确保你做headers = headers.append(...),这样你才能得到新的价值
    • 我已经做到了,但同样的响应,虽然当我与邮递员做同样的请求时,它给出了正确的响应,所以这意味着问题出在角度方面,
    • 在请求头中:访问控制请求头:授权,内容类型
    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 2018-11-28
    • 2020-07-22
    • 2021-11-29
    • 2019-04-26
    • 2020-01-11
    • 2019-07-29
    • 2019-06-11
    相关资源
    最近更新 更多