如何在 Angular 2 中正确设置 Http 请求标头 [英] How to correctly set Http Request Header in Angular 2

查看:38
本文介绍了如何在 Angular 2 中正确设置 Http 请求标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Angular 2 的 Ionic 2 应用程序,它向 ASP.NET Core API 服务器发送一个 Http PUT.这是我用来发送请求的方法:

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);
}

我正在标题对象上设置身份验证键/值.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆