简体   繁体   English

带有自定义标头的Angular 2 Http获得405

[英]Angular 2 Http with custom headers getting 405

I've run into this issue with custom headers when trying to perform and Http GET request from angular 2. Preforming the same request from Postman works fine, however I get a following 405 error in Angular2: 我在尝试执行和角度2的Http GET请求时遇到了自定义标头的问题。从Postman执行相同的请求可以正常工作,但是在Angular2中出现以下405错误:

OPTIONS http://[somehost.com]/api/v1/admin/account/singin 405 (Method Not Allowed)

The API has a GET operation where you pass a username and password in the header and it returns a 200 with a token in it's header. 该API具有GET操作,您可以在标头中传递用户名和密码,并返回标头中带有令牌的200。 Here is an example of the code block I am using: 这是我正在使用的代码块的示例:

constructor (private http: Http) {

}

login (userName: string, password: string): Observable<any> {

  const endPointUrl = this.baseUrl + '/admin/account/singin';

  const headers = new Headers({
    'Accept': 'application/json',
    'X-Rem-Username': userName,
    'X-Rem-Password': password
  });

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

  return this.http.get(endPointUrl, options)
    .map((response: Response) => {
      console.log(response);
      return response;
    });
}

As I mentioned, performing this request in Postman and in he WebStorm REST client with these headers works fine. 正如我提到的,在Postman和WebStorm REST客户端中使用这些标头执行此请求可以正常工作。 If I remove these 'X-Rem' headers I get a 401, which is expected. 如果删除这些“ X-Rem”标头,则会得到401,这是预期的。 Any help would be appreciated, thanks. 任何帮助,将不胜感激,谢谢。

Try this 尝试这个

const headers = new Headers({
    'Accept': 'application/json',
    'X-Rem-Username': userName,
    'X-Rem-Password': password
});

this.http.get('url', {headers: headers})

I am not sure but you can try add this header: 我不确定,但是您可以尝试添加以下标头:

  "Access-Control-Expose-Headers" : "Authorization"

I found it in this discussion 我在这次讨论中找到了

This is not problem with angular app. 这不是角度应用程序的问题。 Your app and rest api server are different server/domain. 您的应用程序和Rest API服务器是不同的服务器/域。 You should configure cross domain allow in server. 您应该在服务器中配置跨域允许。 Whenever you request any api on server by web browser, it first check cross domain allow options by request a OPTION method. 每当您通过网络浏览器在服务器上请求任何api时,它都会首先通过请求OPTION方法检查跨域允许选项。 In postman api directly send, there is no cross domain. 在邮递员api中直接发送,没有跨域。

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

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