Angular 2/4如何添加多个标头到http post
我有添加额外的标题到html post的问题。卷曲的 和邮递员非常相像。 我无法将授权标头添加到发布请求。Angular 2/4如何添加多个标头到http post
我的问题是类似https://stackoverflow.com/questions/39408413/angular2-http-post-how-to-send-authorization-header
我的代码:
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()
)
}
现在,当我试图让这个没有那两个头都没有添加
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
但是,当我评论授权标题,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头和追加授权我有一个像第一次一样的问题 - 不添加标题:/
I'have角4.2 - 安装和纳克CLI
如何升级为POST添加额外的标题?在邮递员的工作完美
=====编辑==== 感谢您的回复,但两个解决方案不起作用
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()
)
}
现在如果我评论“授权”内容类型中加入授权请求I无标头不加入和身体不发送太
=========编辑=========
根据这一话题Angular2 - set headers for every 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()
)
}
我仍然有错误:/头不添加:/
我做了一些调查s,测试。当我尝试只发送'Content-type = application/x-www-form-urlencoded'时,我收到错误'坏客户'的回复,因为我没有发送授权。当我尝试使用授权添加另一个头时出现问题。
我已经做了类似的GET方法,我只能添加'授权'标题,其他。如果我添加的例子,GET方法“X-授权”标头是后改为OPTIONS方法,如:/
在控制台我得到错误:
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发布请求中的标题?
我只在内容中添加了Content-Type标头。我收到了400个代码的答复,因为我的请求没有授权标题。在Firefox中,我编辑了这个请求,在标题中添加了授权,并且我得到了我想要的代码为200的代码:) 所以问题出在Angular上而不是浏览器上。
====编辑==== Spotify说我不应该使用clientid和客户端+秘密。我应该用这个:
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.
,这来自于“回调: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.
但这次这个来自“本地主机/:1
在邮递员我het完整的HTML重定向。我怎样才能使这种重定向的角2
您可以使用拦截把头在每次请求:
本教程将帮助你实现这一目标:
我做什么,工作原理是,
this.options = new RequestOptions({
headers: new Headers({
'header1': 'value1',
// And more
})
});
而且我用我的请求this.options
。
希望这有助于你
您可以设置标题一样,
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');
此外,在角5 类新介绍,您可以设置轻松
header = new HttpHeaders();
header.set('Content-Type', 'application/x-www-form-urlencoded');
好,如果你正在使用最新的角色HttpClient,这很容易。看例子。
this.httpClient.post(url, body, {
headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.getAuthAccessToken())
.set('Content-Type', 'application/json')
})
希望它有帮助。由于
正如我们可以看到,当我尝试添加授权标题然后请求方法更改为OPTIONS而不是POST:/ – nicram
我读了CORS,就是这样。当我尝试添加非标准Header xhr时,首先使用OPTIONS方法来询问允许的标题,但是api spotify不会在POST方法中使用OPTIONS。 CURL直接发送所有标题,因此有很好的答案。有没有办法阻止xhr ro发送OPTIONS方法befor POST? – nicram
你能解决你的问题吗?我想你的代码手动添加头文件并使用默认头文件工作,问题是CORS,它是在服务器上配置的(你没有cURL的问题,因为它不关心原点)。所以当你在浏览器中发布帖子时,它首先发送一个OPTIONS请求(它被称为预检)。服务器检查它。如果没问题,您的浏览器将收到一个OK响应,然后发送POST请求。如果服务器不允许请求,您的浏览器将从OPTIONS请求中收到错误。 – user276648