Shiyal Khushal
Shiyal Khushal

Reputation: 3

How to fetch API with POST method and Authorization Bearer token in javascript?

var get = localStorage.getItem("token"); var token = JSON.parse(get);

  function myfun(){
    fetch(url,{
      method: 'POST',
      headers:{
        "Authorization":`Bearer + ${token}`
      },
      body:JSON.stringify({
        city: account_city.value,
        district: account_dis.value,
        state: account_state.value,
      })
    })
    .then((res)=> res.json())
    .then(data=> console.log(data));
  }

I try this code. Please help!!!!

Upvotes: 0

Views: 3911

Answers (2)

devendra tata
devendra tata

Reputation: 141

Try this, your code looks good, the only issue I am seeing is string Interpolation. What is the issue you are facing

{
        method: "POST",
        url: url,
        data: data,
        headers: { Authorization: `Bearer ${token}` },
      }

Upvotes: 3

Sayydika
Sayydika

Reputation: 178

If you use string interpolation from ES6, you don't need to add + operator to make a concatenation.

So try either : "Authorization": `Bearer ${token}` or "Authorization": "Bearer " + token

Upvotes: 1

Related Questions