How to correctly set Http Request Header in Angular 2

rbasniak picture rbasniak · Dec 14, 2016 · Viewed 141.5k times · Source

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:

enter image description here

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.

What am I doing wrong?

Answer

Paul Jerome Bordallo picture Paul Jerome Bordallo · Dec 14, 2016

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)