Search code examples
angularform-databearer-token

Can't send form data with a bearer token in angular


I'm sending form data to my backend and it's working normally, when i include a bearer token though, it doesn't work and the backend doesn't read the data.

Here's what i'm doing :

Component.ts

send() {
    const formData = new FormData();
    formData.append('title', this.form.value.title);
    formData.append('description', this.form.value.description);

    this.service.add(formData).subscribe(data => {
      console.log(data);
    });
}

Service. In this code back read the data.

add(data) {
    return this.http.post(url, data);
}

But it does not work in this code :

add(data) {
    const headers = new HttpHeaders({
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + localStorage.getItem('token')
    });
    return this.http.post(url, data, {headers});
}

Solution

  • Try like this:

    var header = {
      headers: new HttpHeaders()
        .set('Authorization',  'Bearer ' + localStorage.getItem('token'))
    }
    
     return this.http.post(url, data, header);