Wilmer Demata
Wilmer Demata

Reputation: 95

Fetch API request receives 401 unauthorized access

I am trying to access an API however I was receiving an error code 401. I tried my endpoint on POSTMAN and it's working just fine.

I was able to provide a bearer token on POSTMAN.

if appropriate here is the code.

async function fetchData(){
const response = await fetch('http://192.168.3.143:4040/mmi-endpoints/v0/article/custom_query', {
  method : "POST",
  mode: "cors",
  cache: "no-cache",
  credentials: "include",
  headers: {
    "Content-Type" : "application/json"
  }
})
const data = await response.json()
setData(data)
}

Upvotes: 2

Views: 5777

Answers (1)

dharmey
dharmey

Reputation: 85

You could add the Bearer token to the headers of the request.

const token = 'your-t0ken_xyz'

async function fetchData() {
const response = await fetch('http://192.168.3.143:4040/mmi-endpoints/v0/article/custom_query', {
  method : "POST",
  mode: "cors",
  cache: "no-cache",
  credentials: "include",
  headers: {
    "Content-Type" : "application/json",
    "Authorization": `Bearer ${token}`
  }
})
const data = await response.json()
setData(data)
}

Upvotes: 1

Related Questions