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.
What am I doing wrong?
Your parameter for the request options in http.put() should actually be of type RequestOptions. Try something like this:
Angular 4 >
You can either choose to set the headers manually, or make an HTTP interceptor.
Prerequisites for Angular <4.3:
Please make sure you use
@angular/common/http
throughout your application (this got changed in Angular 4.3).Manually
From the Angular docs.
Setting a header:
Setting multiple headers:
Local variable (immutable instantiate again)
HTTP interceptor
From the Angular docs.
Make sure you use
@angular/common/http
throughout your application. That way your requests will be catched by the interceptor.Step 1, create the service:
Step 2, add it to your module:
Useful links:
For us we used a solution like this:
Reference here
You have a typo.
Change:
headers.append('authentication', ${student.token});
To:
headers.append('Authentication', student.token);
NOTE the Authentication is capitalized
In your app.module import HTTP_INTERCEPTORS from '@angular/common/http'. Then add to your providers the interceptors (AuthInterceptor and responseInterceptor). Doing this your app will consider the interceptors in all our httpClient calls.
At login http response (use http service), save the token at localStorage.
Then use httpClient for all your apirest services.
You can check some good practices on my github proyect here
This should be easily resolved by importing headers from Angular: