I am trying very simple angular 4 http request. When i check chrome developer tools, i couldn't see http headers.
const headers: Headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer: 123213');
this.http.post('https://127.0.0.1:502', JSON.stringify(token), {headers: headers}).subscribe();
am i missing something?
Starting with [email protected].
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.
If you use HttpClient instead Http your code should looks like this:
login(credintials: Authenticate): Observable<any> {
const body = {
username: credintials.username,
password: credintials.password,
grant_type: 'password',
client_id: credintials.client_id
};
const headers = new HttpHeaders()
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Authorization', 'Basic loremlorem');
return this.http.post(`${baseUrl}/uaa/oauth/token`,
body,
{
headers: headers
}
);
}
If your params is optional you should append params like this:
let params: HttpParams = new HttpParams();
if (param) {
params = params.append( 'page', param.page );
}
Source code looks like:
/**
* Construct a new body with an appended value for the given parameter name.
*/
append(param: string, value: string): HttpParams;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With