Angular 2/4 如何将多个 headers 添加到 http post
Angular 2/4 how to add multiple headers to http post
我在向 html post 添加额外的 header 时遇到问题。
与 postman 一样,curl 也能很好地工作。
我无法将授权 header 添加到 post 请求。
我的问题类似于
我的代码:
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()
)
}
现在,当我尝试获取这两个 header 中的 none 时
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
但是当我评论授权 header 时,添加了 Content-Type 并且得到 invalid_client 错误 400
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
但是当我评论 Content-Type header 并附加授权时,我遇到了与第一次相同的问题 - 没有添加 header :/
我有 angular 4.2 - 从 ng cli 安装和升级
如何向 POST 添加额外的 header?在 Postman 中这项工作非常完美
=====已编辑====
感谢您的回复,但这两种解决方案都不起作用
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()
)
}
现在,如果我评论 'Authorization' Content-Type 被添加到授权请求中,我 none header 未添加且 body 未发送太
========= 已编辑 =========
根据这个主题 我创建了 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 };
在app.module.ts
import { requestOptionsProvider, DefaultRequestOptions } from './default-request-options.service'
...
providers: [
requestOptionsProvider
],
现在为我服务
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()
)
}
我仍然有错误 :/ Headers 未添加 :/
我做了一些调查、测试。当我尝试仅发送 'Content-type=application/x-www-form-urlencoded' 时,我收到错误 'bad client' 的回复,因为我没有发送授权。当我尝试通过授权添加另一个 header 时出现问题。
我用GET方法做了类似的,我只能添加'Authorization',header,none其他。例如,如果我添加 "X-Authorization" header,GET 方法将更改为 OPTIONS 方法,如 POST :/
在控制台中出现错误:
XMLHttpRequest cannot load 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. Origin 'http://localhost:4200' is therefore not allowed
access.
有什么方法可以在 http post 请求中提供更多的 header 吗?
我只添加了 Content-Type header 和 body。我收到了 400 代码的回复,因为我的请求未经授权 header。在 firefox 中,我通过向 headers 添加授权来编辑此请求,我得到了我想要的带有令牌的代码 200 :)
所以问题出在 Angular 而不是浏览器。
==== 已编辑 ====
Spotify 说我不应该使用 clientid 和 client+secret。我应该使用这个:
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)
}
)
现在我得到 200,但没有显示回调。在控制台中我有:
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.
这来自 "callback:1"
我已经为回调和 callbackComponent 创建了路由
import { Component } from '@angular/core';
// import { AuthService } from './auth.service';
@Component({
template: `<h2>callback</h2>`
})
export class CallbackComponent {
}
但在控制台中我仍然有错误:/
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.
但这次来自 'localhost/:1
在 postman 中,我已完全 html 进行重定向。如何在 Angular 2
中进行重定向
我所做和工作的是
this.options = new RequestOptions({
headers: new Headers({
'header1': 'value1',
// And more
})
});
我在请求中使用 this.options
。
希望对你有帮助
你可以这样设置header
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');
此外,在Angular 5
新 class 介绍让您可以轻松设置
header = new HttpHeaders();
header.set('Content-Type', 'application/x-www-form-urlencoded');
好吧,如果您使用的是最新的 angular HttpClient,那就很容易了。请参阅示例。
this.httpClient.post(url, body, {
headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.getAuthAccessToken())
.set('Content-Type', 'application/json')
})
希望对您有所帮助。谢谢
您可以利用 拦截器 将 headers 放在每个请求上:
本教程将帮助您完成:
在不使用 new Headers()
的情况下将多个 headers 添加到 http post 的一种方法如下:
$http.post(url, entity, {
headers: {
customHeader1: customHeader1Value,
customHeader2: customHeader2Value
}
}).then(...
希望对您有所帮助。
我在向 html post 添加额外的 header 时遇到问题。 与 postman 一样,curl 也能很好地工作。 我无法将授权 header 添加到 post 请求。
我的问题类似于
我的代码:
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()
)
}
现在,当我尝试获取这两个 header 中的 none 时
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
但是当我评论授权 header 时,添加了 Content-Type 并且得到 invalid_client 错误 400
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
但是当我评论 Content-Type header 并附加授权时,我遇到了与第一次相同的问题 - 没有添加 header :/
我有 angular 4.2 - 从 ng cli 安装和升级
如何向 POST 添加额外的 header?在 Postman 中这项工作非常完美
=====已编辑==== 感谢您的回复,但这两种解决方案都不起作用
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()
)
}
现在,如果我评论 'Authorization' Content-Type 被添加到授权请求中,我 none header 未添加且 body 未发送太
========= 已编辑 =========
根据这个主题
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 };
在app.module.ts
import { requestOptionsProvider, DefaultRequestOptions } from './default-request-options.service'
...
providers: [
requestOptionsProvider
],
现在为我服务
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()
)
}
我仍然有错误 :/ Headers 未添加 :/
我做了一些调查、测试。当我尝试仅发送 'Content-type=application/x-www-form-urlencoded' 时,我收到错误 'bad client' 的回复,因为我没有发送授权。当我尝试通过授权添加另一个 header 时出现问题。
我用GET方法做了类似的,我只能添加'Authorization',header,none其他。例如,如果我添加 "X-Authorization" header,GET 方法将更改为 OPTIONS 方法,如 POST :/
在控制台中出现错误:
XMLHttpRequest cannot load 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. Origin 'http://localhost:4200' is therefore not allowed access.
有什么方法可以在 http post 请求中提供更多的 header 吗?
我只添加了 Content-Type header 和 body。我收到了 400 代码的回复,因为我的请求未经授权 header。在 firefox 中,我通过向 headers 添加授权来编辑此请求,我得到了我想要的带有令牌的代码 200 :) 所以问题出在 Angular 而不是浏览器。
==== 已编辑 ==== Spotify 说我不应该使用 clientid 和 client+secret。我应该使用这个:
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)
}
)
现在我得到 200,但没有显示回调。在控制台中我有:
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.
这来自 "callback:1"
我已经为回调和 callbackComponent 创建了路由
import { Component } from '@angular/core';
// import { AuthService } from './auth.service';
@Component({
template: `<h2>callback</h2>`
})
export class CallbackComponent {
}
但在控制台中我仍然有错误:/
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.
但这次来自 'localhost/:1
在 postman 中,我已完全 html 进行重定向。如何在 Angular 2
中进行重定向我所做和工作的是
this.options = new RequestOptions({
headers: new Headers({
'header1': 'value1',
// And more
})
});
我在请求中使用 this.options
。
希望对你有帮助
你可以这样设置header
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');
此外,在Angular 5 新 class 介绍让您可以轻松设置
header = new HttpHeaders();
header.set('Content-Type', 'application/x-www-form-urlencoded');
好吧,如果您使用的是最新的 angular HttpClient,那就很容易了。请参阅示例。
this.httpClient.post(url, body, {
headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.getAuthAccessToken())
.set('Content-Type', 'application/json')
})
希望对您有所帮助。谢谢
您可以利用 拦截器 将 headers 放在每个请求上:
本教程将帮助您完成:
在不使用 new Headers()
的情况下将多个 headers 添加到 http post 的一种方法如下:
$http.post(url, entity, {
headers: {
customHeader1: customHeader1Value,
customHeader2: customHeader2Value
}
}).then(...
希望对您有所帮助。