Starting with angular@5.x.
the @angular/http
module is deprecated with all its classes. Now angular/common/http
should be used. Read here for more.
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
this.http.post(
"http://localhost:3000/contacts",
JSON.stringify({id: 4, name: 'some'}),
httpOptions
).subscribe();
For the older versions, you can do it like this:
import {Http, Headers, RequestOptions} from '@angular/http';
export class AppComponent {
constructor(private http: Http) {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `hello`);
const options = new RequestOptions({headers: headers});
this.http.post(
"http://localhost:3000/contacts",
JSON.stringify({id: 4, name: 'some'}),
options
).subscribe();
You have to ensure that you're importing correct objects from the @angular/http
:
import {Http, Headers, RequestOptions} from '@angular/http';
If you still don't see your headers, it's also possible that the server you're using doesn't allow them. When a browser makes a request to the other origin, it sends access-control-headers-request header to check if server allows custom header. If your server is not configured to allow custom headers, you will not see them in the consequent requests.