Axios get request response with 403 error forbidden - javascript

I'm new in react . Trying to make "get" request and getting 403 error forbidden, "Response for preflight does not have HTTP ok status.". In network tab in Request Method instead of "get" method shows "options". What could be the problem? Cors already open , problem with token
let token = localStorage.getItem("token")
axios
.get("http://dev.*****************get-template", {
headers: {
Authorization: `Bearer + ${token}`,
},
})
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
that's how I'm saving token. May be I'm not correctly saving it in localStorage? But when console.log it displays fine
event.preventDefault()
const formdata = new FormData()
formdata.append("username", this.state.userLogin.email)
formdata.append("password", this.state.userLogin.password)
axios
.post("http://dev.****************/get-token", formdata)
.then(res => {
if (res.data) {
console.log(res.data)
localStorage.setItem("token", res.data.access_token)
localStorage.setItem("updToken", res.data.update_token)
this.props.history.push("/settings")
}
})
.catch(error => {
console.log(error)
})

I see a problem in your Bearer token
you write it:
Authorization: `Bearer + ${token}`
but it should be :
Authorization: `Bearer ${token}`,
and the full answer is :
let token = localStorage.getItem("token")
axios
.get("http://dev.*****************get-template", {
headers: {
Authorization: `Bearer ${token}`, //here remove + in template litereal
},
})
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})

Do it like this:
let token = localStorage.getItem("token")
axios.defaults.headers.common['Authorization'] = token
axios
.get("http://dev.*****************get-template")
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})

This is due to CORS issue.
To solve this you need to set Access-Control-Allow-Origin header on your server side, allowing the domain from which you are sending the request or you can set it to *

Related

Adding Cookie to Request Header of a Fetch API

The issue I have is Cookie is not added to the request header therefore I receive a 403 status. To explain further I am implementing a system link where when a user opens a page, a request token is is fetched and added to the META of the html and also saved in the document.cookie. When the user decides to login, the fetch request below fetchSignIn should automatically add a cookie because I am setting credentials: "include" but it doesn't. I have looked at other examples but I don't understand where my implementation is wrong.
Login implementation using OOP
class Login {
// Private methods...
fetchSignIn (obj, url) {
console.log("Cookie ", document.cookie);
fetch(url, {
method: "POST",
mode: "cors",
credentials: "include",
body: JSON.stringify(obj),
headers: {
"Content-Type": "application/json",
"Authorization": "",
"X-XSRF-TOKEN": getQSelector('meta[name="_csrf"]').content
}
})
.then((response) => response.text())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error('Error: ', error.message);
});
}
}
Fetch token on opening of the page
window.addEventListener("DOMContentLoaded", (e) => {
_loadCSRF(CSRFDOMLOAD);
})
const _loadCSRF = (path) => {
fetch(path) // GET Request
.then((response) => response.json())
.then((data) => {
console.log(data);
document.cookie = data.headerName + "=" + data.token;
getQSelector('meta[name="_csrf_header"]').setAttribute("content", data.headerName);
getQSelector('meta[name="_csrf"]').setAttribute("content", data.token);
})
.catch((err) => console.error("Failed csrf fetch ", err));
}

Axios request returns 401 despite having an authorization header

I'm trying to patch data to a django API using axios using this snippet:
nextQuestion = () => {
if (this.state.currentIndex === 0) return;
const token = this.props.token;
const configs = {
headers: {
Authorization: `Token ${token}`,
},
data: {
quiztaker: this.state.data[0].quiz.quiztakers_set.id,
question: this.state.data[0].quiz.question_set[this.state.currentIndex]
.id,
answer: Number(this.state.answer),
},
};
console.log(configs);
axios
.patch("/api/save-answer/", configs)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
this.setState({
currentIndex: this.state.currentIndex - 1
});
};
I have confirmed that the token does indeed exist and that it is authorised to access and make changes to that endpoint through insomnia. Did i do anything wrong with how i set up axios? or is there something else i'm not getting? Apologies if it's an obvious mistake, still quite new to react.
With axios.patch() it should be executed axios.patch(url, data, config)....
const data = {
"quiztaker": this.state.data[0].quiz.quiztakers_set.id,
"question": this.state.data[0].quiz.question_set[this.state.currentIndex].id,
"answer": Number(this.state.answer),
};
const token = this.props.token;
const configs = {
"headers": {
"Authorization": `Token ${token}`,
},
};
axios
.patch("/api/save-answer/", data, configs)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});

I'm using axios to make a GET request for a Lord of the Rings API, I'm new to coding, and I'm failing to send the access key properly

componentDidMount() {
axios.get('https://the-one-api.herokuapp.com/v1/movie',{key:'6DMnrpLiKW4BJK1_7X18'}).then((res) => console.log(res)).catch(err => console.log(err))
}
this is a snippet inside a react component (React JS)
Your headers should contain Authorization: Bearer [key], so this should work:
componentDidMount() {
axios.get(
'https://the-one-api.herokuapp.com/v1/movie',
{'Authorization':'Bearer 6DMnrpLiKW4BJK1_7X18'}
)
.then((res) => console.log(res))
.catch(err => console.log(err))
}
From the documentation of the page, you need send the Bearer Authentication header:
const token = '6DMnrpLiKW4BJK1_7X18';
axios.get('https://the-one-api.herokuapp.com/v1/movie', {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then((res) => console.log(res))
.catch(err => console.log(err));

axios post method 400 bad request

I'm getting a JSON file, editing it and trying send it back to server. But when I use post method it throws an error 400 bad request.In response shows "no template_id or no template_json presented". What could be the problem?
saveData() {
const { data } = this.state
let token = localStorage.getItem("token")
axios
.post(
"http://dev.candidates.hrmessenger.com/stage/set-template",
data,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
},
)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
Please try to use this:
data.template_id = 1;
saveData() {
const { data } = this.state
data.template_id = 1;
let token = localStorage.getItem("token")
axios
.post(
"http://dev.candidates.hrmessenger.com/stage/set-template",
data,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
},
)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
You missed the parameter template_id, or you need to ask from your API developer to send the documentations of the POST Method API.

axios preflight http status code 500

I can't seem to make the yelp API work for me. I get past the first ajax but the I get error on the second.
XMLHttpRequest cannot load https://api.yelp.com/v3/businesses/search. Response for preflight has invalid HTTP status code 500
I am running this on localhost:3000 and I'm using Allow-Control-Allow-Origin: * extension on Chrome.
This is my code on client side:
axios({
method: 'post',
url: 'https://api.yelp.com/oauth2/token',
data: 'grant_type=client_credentials'
+ '&client_id='+api[0]
+ '&client_secret='+api[1]
}).then(res => {
USER_TOKEN = res.data.access_token;
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(api[2], { headers: { Authorization: AuthStr } })
.then(res => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
})
.catch((error) => {
console.log('error ' + error);
});

Categories

Resources