简体   繁体   English

Angular 2/4如何将多个标头添加到http发布

[英]Angular 2/4 how to add multiple headers to http post

I've problem with adding additonal headers to html post. 我在向HTML帖子添加附加标头时遇到问题。 with curl works very well like with postman. 卷曲的效果和邮递员一样很好。 I can't add Authorization header to post request. 我无法添加授权标头来发布请求。

my problem is similar to https://stackoverflow.com/questions/39408413/angular2-http-post-how-to-send-authorization-header 我的问题类似于https://stackoverflow.com/questions/39408413/angular2-http-post-how-to-send-authorization-header

my code: 我的代码:

 getToken(){

let headers = new Headers;
headers.append('Authorization', 'Basic ' + btoa(Spotify.clientId + ':' + Spotify.clientSecret));
headers.append('Content-Type', 'application/x-www-form-urlencoded');

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


let params = new URLSearchParams();
params.append('grant_type', 'client_credentials');

 console.log(

  this.http.post(Spotify.tokenUrl, params.toString(), options).subscribe()

)  
}

Now, when I try to get this none of those two headers aren't added 现在,当我尝试获取此标题时,这两个标头都没有添加

OPTIONS /api/token HTTP/1.1
Host: accounts.spotify.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://172.21.7.171:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, 
  like Gecko) Chrome/59.0.3071.86 Safari/537.36
Access-Control-Request-Headers: authorization
Accept: */ *
Referer: http://172.21.7.171:4200/
Accept-Encoding: gzip, deflate, br
Accept-Language: pl,en;q=0.8,en-US;q=0.6

But when I comment Authorization header, Content-Type is added and a get invalid_client with error 400 但是当我注释Authorization标头时,添加了Content-Type并获得了一个error 400的get invalid_client

POST /api/token HTTP/1.1
Host: accounts.spotify.com
Connection: keep-alive
Content-Length: 29
Accept: application/json, text/plain, */ *
Origin: http://172.21.7.171:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, 
 like Gecko) Chrome/59.0.3071.86 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://172.21.7.171:4200/
Accept-Encoding: gzip, deflate, br
Accept-Language: pl,en;q=0.8,en-US;q=0.6

But when I comment Content-Type header and append Authorization I have the same issue like first time - no added header :/ 但是,当我评论Content-Type标头并追加授权时,我遇到了与第一次相同的问题-没有添加标头:/

I'have angular 4.2 - installed and upgraded from ng cli 我有Angle 4.2-已从ng cli安装并升级

How to add additonal headers to POST? 如何将附加标头添加到POST? in Postman this work perfect 在邮递员中,这项工作很完美

在此处输入图片说明

===== Edited ==== Thanks for reply, but both solutions don't work =====已编辑====谢谢您的答复,但两种解决方案均无效

getToken(){

let options = new RequestOptions();
  options.headers = new Headers();
  options.headers.append('Authorization', Spotify.token);
  options.headers.append('Content-Type', 'application/x-www-form-urlencoded')

let params = new URLSearchParams();
params.append('grant_type', 'client_credentials');

 console.log(
  this.http.post(Spotify.tokenUrl, params.toString(), options).subscribe()
) 
}

now if I comment 'Authorization' Content-Type is added to Request with AUthorization i none header isn't added and body isn't sent too 现在,如果我评论“授权”内容类型已添加到带有AUthorization的请求中,则不会添加任何标题,也不会发送正文

========= edited ========= =========编辑=========

According to this topic Angular2 - set headers for every request I've created default-request-options.service.ts 根据这个主题Angular2-为我创建的每个请求设置标头 default-request-options.service.ts

import { Injectable } from '@angular/core';
import { BaseRequestOptions, RequestOptions, Headers } from '@angular/http';

@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions {

    private superHeaders: Headers;

    get headers() {
        // Set the default 'Content-Type' header
        this.superHeaders.set('Content-Type', 'application/json');

        const token = localStorage.getItem('authToken');
        if(token) {
            this.superHeaders.set('Authorization', `Bearer ${token}`);
        } else {
            this.superHeaders.delete('Authorization');
        }
        return this.superHeaders;
    }

    set headers(headers: Headers) {
        this.superHeaders = headers;
    }

    constructor() {
        super();

    }
}

export const requestOptionsProvider = { provide: RequestOptions, useClass: DefaultRequestOptions };

in app.module.ts 在app.module.ts中

import { requestOptionsProvider, DefaultRequestOptions } from './default-request-options.service'
...
providers: [
    requestOptionsProvider
  ],

now in my service 现在为我服务

import { DefaultRequestOptions } from '../default-request-options.service';
  getToken(){

    let params = new URLSearchParams();
    params.append('grant_type', 'client_credentials');

    let options = new DefaultRequestOptions();
      //options.headers = new Headers();
     // options.headers.append('Authorization', Spotify.basicCode);
      //options.headers.append('Content-Type', 'application/x-www-form-urlencoded');
      // options.body = params.toString();
      // options.method = 'post';

   console.log(
      this.http.post(Spotify.tokenUrl, params.toString(), options).subscribe()
      ) 

  }

And I have errors still :/ Headers aren't added :/ 而且我仍然有错误:/没有添加标题:/

I've made some investigations, tests. 我做了一些调查,测试。 When I try send only 'Content-type=application/x-www-form-urlencoded' I get reply with error 'bad client' because I don't send Authorization. 当我尝试仅发送“ Content-type =应用程序/ x-www-form-urlencoded”时,由于未发送授权,因此收到错误“坏客户”的回复。 Problem occours when I try to add another header with Authorization. 当我尝试使用授权添加另一个标题时,出现了问题。

I've made similar with GET method and I can add only 'Authorization' header, none other. 我已经使用GET方法进行了类似的操作,并且只能添加“ Authorization”标题。 If I added for example "X-Authorization" header that GET method is changed to OPTIONS method like in POST :/ 例如,如果我添加了“ X-Authorization”标头,则GET方法将变为POST中的OPTIONS方法:/

In console I get error: 在控制台中,我得到错误:

XMLHttpRequest cannot load https://accounts.spotify.com/api/token . XMLHttpRequest无法加载https://accounts.spotify.com/api/token Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 对预检请求的响应未通过访问控制检查:请求的资源上不存在“ Access-Control-Allow-Origin”标头。 Origin ' http://localhost:4200 ' is therefore not allowed access. 因此,不允许访问源' http:// localhost:4200 '。

Is there any way to provide more in one header in http post request? 有什么办法可以在http post请求中的一个标头中提供更多信息?

I added only Content-Type header with body. 我只在正文中添加了Content-Type标头。 I got reply with 400 code because my request was without Authorization header. 因为我的请求没有Authorization标头,所以我得到了400条代码的答复。 In firefox I edited this reqest by adding Authorization to headers and I got what I wanted code 200 with token :) So the problem is with Angular not with browser. 在firefox中,我通过在标题中添加授权来编辑此请求,然后我得到了我想要的带有令牌的代码200 :)因此问题出在Angular而不是浏览器。

==== EDITED ==== Spotify says that i shouldn't use clientid and client+secret. ====编辑==== Spotify说我不应该使用clientid和client + secret。 i should use this: 我应该使用这个:

 let options = new RequestOptions()
      options.headers = new Headers();
      options.params = new URLSearchParams();
      options.params.append('client_id', Spotify.clientId);
      options.params.append('redirect_uri', 'http://localhost:4200/callback');
      options.params.append('scope', 'user-read-private user-read-email');
      options.params.append('response_type', 'token');
      options.params.append('state', '789935');

this.http.get('https://accounts.spotify.com/authorize', options )
        .subscribe(
          res=> {
            console.log('res',res)
          }
        )

now i get 200 but callback isnt displayed. 现在我得到200,但未显示回调。 in console i have: 在控制台中,我有:

XMLHttpRequest cannot load https://accounts.spotify.com/authorize?client_id=2100FakeClientId45688548d5a2b9…scope=user-read-private%20user-read-email&response_type=token&state=789935. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

and this comes from "callback:1" 来自“ callback:1”

I've made route for callback and callbackComponent 我已经为callback和callbackComponent做了路由

import { Component } from '@angular/core';
// import { AuthService } from './auth.service';

@Component({
  template: `<h2>callback</h2>`
})
export class CallbackComponent {

}

but in console I've error still :/ 但是在控制台中我仍然出错:/

localhost/:1 XMLHttpRequest cannot load https://accounts.spotify.com/authorize?client_id=21006d1ceeFakeClient548d5a2b9…scope=user-read-private%20user-read-email&response_type=token&state=789935. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

but this time this comes from 'localhost/:1 但这一次来自'localhost /:1

In postman I het full html to redirect. 在邮递员中,我用全HTML重定向。 How can I make this redirection in Angular 2 如何在Angular 2中进行此重定向

Well, if you are using latest angular HttpClient, it is very easy. 好吧,如果您使用的是最新的Angular HttpClient,则非常简单。 See the example. 参见示例。

this.httpClient.post(url, body, {
      headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.getAuthAccessToken())
      .set('Content-Type', 'application/json') 
    })

Hope it helps. 希望能帮助到你。 Thanks 谢谢

You can make use of Interceptors to put headers on every request: 您可以使用拦截器在每个请求上放置标头:

This tutorial will help you accomplish that: 本教程将帮助您完成以下任务:

https://medium.com/codingthesmartway-com-blog/angular-4-3-httpclient-accessing-rest-web-services-with-angular-2305b8fd654b https://medium.com/codingthesmartway-com-blog/angular-4-3-httpclient-accessing-rest-web-services-with-angular-2305b8fd654b

you can set header like that 你可以像这样设置标题

 let options = new RequestOptions();
    options.headers = new Headers();
    options.headers.append('Authorization', 'Basic ' + btoa(Spotify.clientId + ':' + Spotify.clientSecret));
    options.headers.append('Content-Type', 'application/x-www-form-urlencoded');

Also, in Angular 5 new class introduce so you can set easily 另外,在Angular 5中引入了新类,因此您可以轻松设置

header = new HttpHeaders();
header.set('Content-Type', 'application/x-www-form-urlencoded');

What I do and works is that 我的工作是

  this.options = new RequestOptions({
    headers: new Headers({
      'header1': 'value1',
      // And more
    })
  });

And I use this.options in my requests. 我在请求中使用this.options

Hope this helps you 希望这对您有帮助

One way to add multiple headers to http post without using new Headers() would be the following: 在不使用new Headers()情况下将多个标题添加到http帖子的一种方法是:

$http.post(url, entity, {
    headers: {
      customHeader1: customHeader1Value,
      customHeader2: customHeader2Value
    }
  }).then(...

I hope it helps. 希望对您有所帮助。

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

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