简体   繁体   English

Angular2无法设置HTTP标头授权

[英]Angular2 unable to set HTTP header authorization

I've a service called ProjectService , where the following code exists: 我有一个名为ProjectService的服务,其中存在以下代码:

..... # skip codes
getProjects(): Observable<any> {
    let url = API.MAIN_URL + '/api/project/';
    return this.http.get(url, this.requestHeaders())
      .map(this.extractData)
      .catch(this.handleErrorObservable);
  }

..... # skip codes
requestHeaders(): any {
    let headers = new Headers();
    headers.append('Access-Control-Allow-Origin', '*');
    headers.append('Authorization', 'token ' + localStorage.getItem('token'));
    let options = new RequestOptions({headers: headers});
    return options;
  }

In my ProjectComponent I tried to subscribe the getProjects() from ProjectService via following code: 在我的ProjectComponent中,我尝试通过以下代码从ProjectService订阅getProjects()

ngOnInit() {

    this._projectService.getProjects().subscribe(data => {
        this.projects = data;
      },
      error => this.message = this.errorMessage(error._body));

  } 

The problem is, whenever my ProjectComponent loads, my console gives me following error: 问题是,每当我加载ProjectComponent时,控制台都会给我以下错误:

Response for preflight has invalid HTTP status code 401 预检的响应具有无效的HTTP状态代码401

I go to my browsers network panel to see the error, it shows that 我转到浏览器网络面板以查看错误,它表明

"Authentication credentials were not provided." “未提供身份验证凭据。”

means that my request doesn't have any authorization token. 表示我的请求没有任何授权令牌。

I've used the ModHeader plugin. 我使用了ModHeader插件。 then added the token there like token eaab49d1dd392bda3fb807f33e1eb296897efc79 in the Authorization hash value. 然后将令牌像token eaab49d1dd392bda3fb807f33e1eb296897efc79一样添加到Authorization哈希值中。
And it works like a charm! 它就像一个魅力!

Don't know how to solve the problem. 不知道如何解决问题。

EDIT: Updating answer to reflect comments 编辑:更新答案以反映评论

This is due to your OPTIONS request that Angular makes. 这是由于Angular提出了您的OPTIONS请求。 Add an additional endpoint of type HttpOptions that returns a status 200 OK , also ensure that this endpoint does not require authentication. 添加类型为HttpOptions的附加端点,该端点返回状态200 OK ,并确保该端点不需要身份验证。

Maybe it's help you: 也许对您有帮助:

let headers = new Headers({ *your headers* });
let options = new RequestOptions({ withCredentials: true, headers });

then try 然后尝试

http.get(url, options)

Try to create headers this way : 尝试通过以下方式创建标题:

setHeaders()
{
    this.headers = new Headers
    ({
        'authorization': localStorage.getItem('token')
    });
}

and send request method: 并发送请求方法:

send_request_get(url: any)
{
    this.setHeaders();
    let options = new RequestOptions
    (
        {
            headers: this.headers
        }
    );

    return this.http.get(url,options )
    ...
}

Don't laugh, but I'm sure this is the most lame answer of my question above. 不要笑,但是我敢肯定,这是我上面问题中最la脚的答案。 I just changed the following lines: 我只是更改了以下几行:

let headers = new Headers();
let options = new RequestOptions({headers: headers});

To this: 对此:

const headers = new Headers();
const options = new RequestOptions({headers: headers});

Then It works! 然后就可以了!

Also, I'm using Http previously, then I switched to HttpClientModule . 另外,我以前使用的是Http ,然后切换到HttpClientModule But of them are working now. 但是他们现在正在工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM