0

I am trying to set header from http post call, But When I am consoling it to the log, It is printing undefined.

I tried the same for params also, but it is not getting set.

callAddGroupAPI(formId, data){
    const headers = new Headers()
    .set('Content-Type', 'application/json');
    console.log(headers);
}

I am expecting output in the console to log the value of headers, But it is print undefined.

I have also tried

callAddGroupAPI(formId, data){
    const headers = new Headers();
    headers.append('Content-Type','application/json');
    console.log(headers);
}

And this also is not working...

I am getting the same problem when I am using

const data = new FormData();
data.set('key', 'value')
console.log(data)

I have use .append() also, But that also is not working.

3 Answers 3

3

This is an example how you set header in post request

create(custom: CustomObject): Observable<CustomObject> {
    const header = new Headers({ 'Content-Type': 'application/json' });
    return this.http.post(this.url, JSON.stringify(custom), { headers: header })....}
Sign up to request clarification or add additional context in comments.

Comments

2

To use headers try this,

// define in your service.ts constructor
this.httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json', 'X-CSRFToken': csrf }),
};

// use 
this.http.post(yoururl, payload, this.httpOptions);

About formdata, when you do console.log() it'll just printFormData {}, to access the key do data.getAll('key') or use data.forEach

Comments

2

You can try this:

import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json'
  })
};

And httpOptions pass in as parameter in your post request

myRequest (item: Item): Observable<Item> {
  return this.http.post<Item>(yourUrl, item, httpOptions)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.