Abh*_*hek 3 typescript angular
我在Angular2 TypeScript中有这个代码,我试图添加如下所示的标题.
['access-token', localStorage.getItem( 'token' )],
['client', localStorage.getItem( 'client' )],
['uid', localStorage.getItem( 'email' )],
['withCredentials', 'true'],
['Accept', 'application/json'],
['Content-Type', 'application/json' ]
Run Code Online (Sandbox Code Playgroud)
在发送请求时,我无法在请求中看到标头.我正在进行跨域设置.还有其他方法吗?
private _request(url: string | Request, options?: RequestOptionsArgs) : Observable<Response> {
let request:any;
let reqOpts = options || {};
let index:any;
if(!reqOpts.headers) {
reqOpts.headers = new Headers();
}
for( index in this._config.authHeaders ) {
reqOpts.headers.set( this._config.authHeaders[index][0], this._config.authHeaders[index][1] );
}
request = this.http.request(url, reqOpts);
return request;
}
Run Code Online (Sandbox Code Playgroud)
如果您的请求是跨域请求,则适用CORS概念.您可以查看这些链接以获取更多详细信息:http://restlet.com/blog/2015/12/15/understanding-and-using-cors/和http://restlet.com/blog/2016/09/27 /如何修复cors-problems /.当然,正如Günter所说,在服务器端有一些事情要做,以返回CORS标头以允许浏览器处理响应.
以下是在HTTP请求中添加标头的示例服务:
export class MyService {
constructor(private http:Http) {
}
createAuthorizationHeader(headers:Headers) {
headers.append('Authorization', 'Basic ' +
btoa('a20e6aca-ee83-44bc-8033-b41f3078c2b6:c199f9c8-0548-4be7-9655-7ef7d7bf9d33'));
}
getCompanies() {
var headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.get('https://angular2.apispark.net/v1/companies/', {
headers: headers
}).map(res => res.json());
}
Run Code Online (Sandbox Code Playgroud)
编辑
我刚看到你试图设置withCredential标题.我认为你混合了不同的东西.withCredentials不是标准头,但withCredentialsXHR JavaScript对象上有一个属性.请参阅此链接:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials.这应该不使用withCredentials自定义标头.
提醒一下,如果要使用自定义标头,则需要在Access-Control-Allow-Headers标头中的服务器端添加它.
希望它对你有帮助,蒂埃里
| 归档时间: |
|
| 查看次数: |
4731 次 |
| 最近记录: |