如何在Angular 2中正确设置Http请求标头 [英] How to correctly set Http Request Header in Angular 2
问题描述
我有一个使用Angular 2的Ionic 2应用程序,它将Http PUT发送到ASP.NET Core API服务器。这是我用来发送请求的方法:
I have an Ionic 2 application using Angular 2, which is sending an Http PUT to a ASP.NET Core API server. Here's the method I'm using to send the request:
public update(student: Student): Promise<Student>
{
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `${student.token}`);
const url = `${this.studentsUrl}`;
return this.http
.put(url, JSON.stringify(student), { headers: headers })
.toPromise()
.then(() => student)
.catch(this.handleError);
}
我在header对象上设置了身份验证密钥/值。
I'm setting an authentication key/value on the headers object.
但是当我在服务器上收到此请求时,我在标题上找不到验证密钥:
But when I receive this request on the server, I cannot find the authentication key on the header:
正如您在图片中看到的那样,标题上有许多键,但不是我的内容和身份验证密钥手动添加到客户端应用程序的标题中。
As you can see in the picture, there are many keys on the header, but not the content and authentication keys that I manually added to the header in the client application.
我做错了什么?
推荐答案
http.put()中请求选项的参数实际上应该是RequestOptions类型。尝试这样的事情:
Your parameter for the request options in http.put() should actually be of type RequestOptions. Try something like this:
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `${student.token}`);
let options = new RequestOptions({ headers: headers });
return this.http
.put(url, JSON.stringify(student), options)
这篇关于如何在Angular 2中正确设置Http请求标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!