Home > Mobile >  Angular ignores given HttpHeaders for post request
Angular ignores given HttpHeaders for post request

Time:10-25

I am using json-server and want to request data as post method with request body. It works with Postman but not with Angular. In Angular is the content type allways text/plain no matter what i am trying. What i am missing?

getProjects(request: ProjectRequest): Observable<Project[]> {
const headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', localStorage.getItem('accessToken')!);

const body = JSON.stringify(request);

return this.http.post<Project[]>(this.apiGetProjects, body, { headers: headers });
}

enter image description here

CodePudding user response:

You don't have to stringify the body. Just do this

this.http.post<Project[]>(this.apiGetProjects, request, { headers: headers });

OffTopic

  1. Don't set the content-type header. Angular will do it for you.
  2. Don't set the authorization header here. Just use a HttpInterceptor. Look at this.
  • Related