Angular web service call not sending headers - javascript

I m trying to call a web service from Angular. I m passing the headers as HttpHeaders object, but I do not see that sent when I check the Network console.
This other post Angular HttpClient doesn't send header
seems to have answered it, but I am not able to get that working with the solution that is suggested in it .
My call looks like this.
1
this.http.get(urlString, {headers: new HttpHeaders({'Content-Type': 'application/json',
'header1': 'value1',
'header2': 'value2'
})});
2
let myHeaders = new HttpHeaders();
myHeaders = myHeaders.set( 'Content-Type', 'application/json')
.set( 'header1', 'value1')
.set( 'header2', 'value2')
;
this.http.get(urlString, {headers: myHeaders});
3
const httpOptions = {
headers: new HttpHeaders(
{ 'Content-Type': 'application/json',
'header1': 'value1',
'header2': 'value2'
})
};
this.http.get(urlString, httpOptions);
In all cases, the Network console shows this
Access-Control-Request-Headers:content-type,header1,header2
Is there some mistake which I am making when I declare or set it? Sorry if this question is repetition of others, but the answers were not working in this code. Thank you.

Use Headers instead of HttpHeaders
const headers = new Headers({'Content-Type' : 'application/json','header1':'value1','header2':'value2'})
return this.http.get('url', {headers: headers});

Related

angular 7 not sending header on request

I'm trying to send content-type headers for the below post request to allow json request, but it throws me an error Invalid CORS request with OPTIONS request method. It doesn't even send POST method.
Here, I cannot able to use RequestOptions which is depreciated.
PS: This is working fine when I send the request with postman. And, Backend code is handled with CORS request already.
From Backend java code, this the error I'm getting
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
Where am I missing?
postSubmit(){
let data = { "name":"John", "age":30 };
const httpHeaders = new HttpHeaders ({
'Content-Type': 'application/json'
});
return this.http.post<any>(apiURL, data, {headers : httpHeaders})
.pipe(catchError(error => this.handleError(error)))
}
}
To define the content-type with the new HttpHeaders class you need to
Just Import import { HttpHeaders } from '#angular/common/http';
Create httpOptions object that will be passed to every HttpClient save method
import { HttpHeaders } from '#angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
Call the API this.http.post<Datatype>(API url, Bady Parameter, httpOptions)

Send custom header with Angular 5

I am trying to send a custom HTTP Header from the front end app for it to interact with the gateway. This is my angular function:
import {Http, Headers, Response, RequestOptions } from ‘#angular/http’;
getXById(id :number){
let options = nee RequestOptions({ headers : new Headers({“X-fastgate-resource” :”resource_name}) });
return this.http.get( http://url + “/resource”, options)
I expected to see a Header with, “X-fastgate-resource” as a key, and “resource_name” as value.
What I got was this:
Request Headers:
OPTIONS http://url HTTP/1.1
host...
Access-Control-Request-Headers: x-fastgate-resource
You could try out something like below.
let headers = new HttpHeaders();
headers.append('X-fastgate-resource', 'Example');
let options = { headers: headers };
let apiUrl: string = 'http://url';
this.http.get(apiUrl, options);
Hope this helps
Try This code:
import {HttpHeaders} from '#angular/common/http';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
**With params**
const url = 'yourapi';
return this.http.post(url, {
key: value,
key1: value1
},httpOptions);
**Without Params**
const url = 'yourapi';
return this.http.post(url,httpOptions);
Try using the Angular Context.
Angular Context
This is the simplest way I know of passing data, usually to an interceptor
Define a Context Token - usually in the interceptor
export const MY_FILENAME = new HttpContextToken<string>(() => "");
Pass the data
const context = new HttpContext().set(MY_FILENAME, `${name}.pdf`)
return this.httpClient.post(url, pdf, {context: context})
Collect the data. Usually in the interceptor
const fileName = request.context.get(MY_FILENAME)

Basic Authentication Angular2 (Not CORS)

I am currently trying to call a jersey REST API that I have running locally on localhost:8080 through Angular 4 using HttpClient.
My Code:
```
ngOnInit() {
const headers = new HttpHeaders();
headers.append('Authorization', 'Basic ' + btoa('username:password'));
headers.append('Content-Type', 'application/json');
this.http.get('http://localhost:8080/mycall?myparam=myvalue', {headers: headers}).subscribe(data => {
console.log(data);
});
}
```
When I make this call I get a 401 error saying that I am Unauthorized. However, when I run this through postman it goes through just fine. What am I doing wrong here?
NOTE: this is not a CORS issue, I am currently allowing CORS through an extension on firefox
HttpHeaders are immutable, so you need to do something like that
ngOnInit() {
const headers = new HttpHeaders()
.append('Authorization', 'Basic ' + btoa('username:password'))
.append('Content-Type', 'application/json');
this.http.get('http://localhost:8080/mycall?myparam=myvalue', {headers: headers}).subscribe(data => {
console.log(data);
});
}
Actually you should not need the Content-type here for a GET request
I think the issue is that you haven't passed in your custom request headers to HttpClient, which is causing the unauthorised error.
Please try something like this.
const headers = new HttpHeaders();
headers.append('Authorization', 'Basic ' + btoa('username:password'));
headers.append('Content-Type', 'application/json');
const options = new RequestOptions({headers: headers});
this.http.get('http://localhost:8080/mycall?myparam=myvalue', options ).subscribe(data => {
console.log(data);
});
You can simply pass in your RequestOptions to http.get as it does accept headers as an optional parameter. Please check following link for more details on the usage.
https://angular.io/api/common/http/HttpClient#get
Also, remember to import RequestOptions as well.

angular rest api call returns https status code 401 ,authentication required

I am hitting an api for getting userinfo, for that I am passing header authorization with value, but in options method it is firing and giving error that https status code 401, authentication required.
I am trying the same with Chrome browser and Postman client tool then it's giving me desired result. Why only my app is throwing such error? It's supposed to give me result if I am giving authorization header for that.
For instance, code is like:
this.http.get(this.url,{headers:this.headers});
Try setting withCredentials : true .
Here is my Working Code. Hope it helps. Also note Iam using new httpclient of Angular 5.
emailsignin(username: string, password: string) { .
let url = this.backendUrl + "/index";
let params = 'username='+username+'&password='+password;
let httpheaders = new HttpHeaders(
{
'Content-Type': 'application/x-www-form-urlencoded'
});
return this._httpclient.post(url, params, {headers: httpheaders, withCredentials : true});
}
You should define your options as a RequestOptions object:
let options = new RequestOptions({ headers: new Headers({ 'Authorization': 'Basic xxxx' }) });
this.http.get(this.url,options );

Send data in a http post in angular 2?

I'm trying to send data with http post following differents threads, but I can't do it.
I need to send this data, tested in postman.
Headers.
Content-Type: application/x-www-form-urlencoded
Authorization: Basic user:pass
Body.
grant_type: password
scope: profile
This is my code.
login() {
let url = URL_LOGIN;
let headers = new Headers(
{
'Content-Type': 'application/json',
'Authorization': 'Basic user:pass'
});
let body = {
'grant_type': 'password',
'scope': 'profile'
}
return this.http.post(url, body, { headers: headers })
.map((response: Response) => {
var result = response.json();
return result;
})
}
Thanks in advance!!
There are two things you need to modify:
Your headers passed into the http post method missed one step. It should contain the following:
let options = new RequestOptions({ headers: headers });
Ensure you import RequestOptions from #angular/http
Then pass options into your post method as follows:
return this.http.post(url, body, options)...
The http post method body can only be a string. Therefore, it should be as follows:
let body = 'grant_type=password' + '&scope=profile';

Categories