在获取请求角度2上设置标头 [英] Set headers on get request angular 2

查看:328
本文介绍了在获取请求角度2上设置标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将一个授权标头设置为GET请求,以向其他API验证用户。我使用Angular 2 RC1。 (我是一个初学者)。

I try to set an Authorization header to a GET request to authenticate users to a rest API. I'm using Angular 2 RC1. (I'am a total beginner).

getTest(){
    let authToken = localStorage.getItem('auth_token');
    let headers = new Headers({ 'Content-Type': 'application/json' });
    headers.append('Authorization', `Bearer ${authToken}`);

    let options = new RequestOptions({ headers: headers });
    return this._http
      .get(this._url,options)
      .map(res => console.log(res));
  }

我允许CORS在我的后端。

I allow CORS in my backend.

header("Access-Control-Allow-Origin: *");
header("Access-Control-Request-Headers: Content-Type, Authorization");

我的控制台:


OPTIONS api / userProfile /

OPTIONS api/userProfile/

XMLHttpRequest无法加载/ userProfile /。对预检的响应有
无效的HTTP状态代码406

XMLHttpRequest cannot load /userProfile/. Response for preflight has invalid HTTP status code 406

我的要求标题

任何想法?

推荐答案

我认为你需要接受标题,而不是因为406状态代码...

I think that you need the Accept header rather because of the 406 status code...

let authToken = localStorage.getItem('auth_token');
let headers = new Headers({ 'Accept': 'application/json' });
headers.append('Authorization', `Bearer ${authToken}`);

let options = new RequestOptions({ headers: headers });
return this._http
  .get(this._url,options)
  .map(res => console.log(res));

这样可以告诉服务器您在响应中需要的内容类型...

This allows you to tell the server which content type you expect in the response...

Content-Type 头部是指定在请求中发送的内容的类型。在你的情况下,没有内容...

The Content-Type header is rather to specify the type of the content you sent in the request. In your case, there is no content...

这篇关于在获取请求角度2上设置标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆