0

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!!!!

5
  • the code looks right, what's the problem? Only problem I see is, token are suppose to be string, why do you need JSON.parse? You should do a console.log(token) to see what is the in your "token". Commented Nov 29, 2020 at 12:54
  • please provide an error message or clarify both required and actual behavior Commented Nov 29, 2020 at 12:56
  • Show where myfun() is being called too. Apart from not knowing where the account variables are coming from, it looks correct. Do you know how to await for the promise to resolve? Commented Nov 29, 2020 at 12:57
  • @amankkg The error message is "500 (Internal Server Error)" Commented Nov 29, 2020 at 13:20
  • 500 (Internal Server Error) that's a problem with (your?) server code Commented Nov 30, 2020 at 3:19

2 Answers 2

3

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}` },
      }
Sign up to request clarification or add additional context in comments.

1 Comment

ok, I try this but it's still not working. I can't post in my API
1

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

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.