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)
})
Describe the bug
I used axios for HTML parsing in my project.
Axios receives a 403 response from a specific URL.
For example, https://www.coupang.com/
I found a solution by comparing node-fetch and axios.
The solution is to add Accept-Encoding to the header.
To Reproduce
const axios = require("axios"); const url= "https://www.coupang.com/"; axios.get(url).then((res) => { console.log('no Accept-Encoding status:', res.status); }) .catch((error) => { console.error('no Accept-Encoding status:', error.response.status); }); const config = { headers: { 'Accept-Encoding': 'gzip, deflate, br' } }; axios.get(url, config).then((res) => { console.log('Accept-Encoding status:', res.status); }) .catch((error) => { console.error('Accept-Encoding status:', error.response.status); });
Expected behavior
If you make a request without Accept-Encoding, you will receive a 403 response.
However, if you request by adding Accept-Encoding, you will receive 200 responses.
Environment
- Axios Version ^0.24.0
- Adapter HTTP/HTTPS
- Node.js Version v14.17.3
- OS: windows10 x64
Additional context/Screenshots
Answer by Anderson Marks
Stack Overflow
Public questions & answers
,
Stack Overflow for Teams
Where developers & technologists share private knowledge with coworkers
,Stack Overflow en español
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)
})
Answer by Issac Harper
Try this It works for me
npm i js-cookie
import Cookies from 'js-cookie'
const csrftoken = Cookies.get('csrftoken') // Cookies from Django Domain
const loginRequest = async () => {
await Axios({
method: "post",
url: `/api/api-auth/login/`,
headers: { 'X-CSRFToken': csrftoken },
data: {}
}).then((res) => {
console.log(res.data);
})
}
Answer by Aiden Franklin
Getting a 403 error instead.,Code snippet to illustrate your question
Call to server.,How to fix this error?
export const invest = (itemid, amount) => async dispatch => {
console.log("investing in actions")
const domain = 'localhost:3000'
const res = axios.post(domain + '/api/invest', {itemid: itemid, amount: amount});
console.log("response is", res)
dispatch({ type: INVESTED, payload:res.data});
}
Answer by Londyn Prince
What is the current behavior?
Whenever I try to create objects from the front-end JS I get error 403 forbidden, even though I supply a valid jwt. I can be able to use Postman and create objects without getting error 403,What is the expected behavior?
I should be able to get the Post back in the response object,
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
newPost: function () {
// Request API.
axios
.post(`http://localhost:1337/posts`, {
headers: {
Authorization: `Bearer ${this.$session.get('jwt')}`
},
caption: this.caption + '',
profile: this.$session.get('profile_id')
})
.then(response => {
// Handle success.
console.log(
'Well done, your post has been successfully created: ',
response.data
)
})
.catch(error => {
// Handle error.
console.log('An error occurred:', error)
})
}
Answer by Avi Haynes
hi,i am working locally on a website,i have to do a get api request,i am using axios module, but there is an error, the console show a 403 error “(forbidden)” i think that it has something to do with CORS but i didn’t succed to fix it,i have to use headers,here is the code:,Actually i tried using proxies it didn’t work too,the console shows the same error,Try using proxies to get by apps forbidden by cors.
https://corsproxy.github.io/
https://cors-anywhere.herokuapp.com/
hi,i am working locally on a website,i have to do a get api request,i am using axios module, but there is an error, the console show a 403 error “(forbidden)” i think that it has something to do with CORS but i didn’t succed to fix it,i have to use headers,here is the code:
var headers = {
'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com',
'X-RapidAPI-Key' : 'c7ff39f1ccmsh87edde31cc65e31p12da7ajsn4e97b9ad7a1e',
}
axios({
method:'get',
url:"https://api-football-v1.p.rapidapi.com/fixtures/live",
headers: headers,
withCredentials: true
})
.then((response) => { console.log(response) } )
}
Answer by Bailee Greer
When I call my Amazon API Gateway API, I get a 403 Forbidden error. How do I troubleshoot the error?,Handling errors in Amazon API Gateway,API Gateway APIs can return 403 Forbidden responses for any of the following reasons:
curl -X GET -v https://apiId.execute-api.region.amazonaws.com/stageName/resourceName
Answer by Alden Chapman
I am working on a web application with a backend in Django and a frontend in React. Currently I am able to create articles through my superuser account and list them on the frontend. I am now trying to create and update but I keep getting the following error:,
Pandas using map or apply to make a new column from adjustments using a dictionary
August 21, 2021
,
useLocation only loading navbar on refresh and not on initial render
August 21, 2021
I am working on a web application with a backend in Django and a frontend in React. Currently I am able to create articles through my superuser account and list them on the frontend. I am now trying to create and update but I keep getting the following error:
xhr.js:184 POST http://127.0.0.1:8000/api/ 403 (Forbidden)
Error: Request failed with status code 403
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:69)
In my research I believe that the error message deals with csrftoken. I have tried adding the following statements in my axios.post request:
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN'
And I have tried adding the following statements in my settings.py file:
CORS_ORIGIN_ALLOW_ALL = True
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
...
]
INSTALLED_APPS = [
...
'corsheaders',
...
]
Answer by Alma Cordova
Answer by Benjamin Lindsey
The HTTP 403 Forbidden client error status response code indicates that the server understood the request but refuses to authorize it.,Report a problem with this content on GitHub,HTTP response status codes
403 Forbidden
Answer by Rocco Houston
request failed with status code 403(forbidden) in axios.get
,
request failed with status code 403(forbidden) in axios.get ,
Questions
Answer by Reuben Parrish
axios.get returns 403 (Forbidden), but axois.post works just fine when working with localhost:port/request_url. However, if I make a request to an outside api with the «.get» method, I get a response with no error; everything works just fine.,I can get the data when entering it in the url bar in the browser like so: localhost:3000/endpoint. I can also get the data from postman. I just can’t get it with axios,When I get an error, I can see that I get a response if I look at the «err.response» object, but because of the error(which is caused by whatever), 403 forbidden is the final result. Any suggestions on a fix? Thanks.
I am working on an application using React+Redux and using axios
to make api calls.
Here’s a sample call which fails:
axios.post(`${API_ROOT}${FIND_USER}${currentUserID}`, {
headers: {
'Authorization': token
},
})
.then((response) => {
console.log("Sucess")
})
Request url when I see in network
is something like:
http://domainName:8080/users/findUser/1234
API call fails at OPTIONS
itself and error I am receiving from backend is
Response for preflight has invalid HTTP status code 403
It never reaches POST
.
token
is retrieved from localstorage
and is something like Bearer eyJhbGci...
.
Backend developers are using Java and Spring .
Is there something wrong in the way I am calling the APIs or this problem should be resolved in the Backend?
This API works totally fine when tested through Postman.
I have a feature that loads a map onto a page, and 5% of the time I’m hit with a 403 error and the map data doesn’t load properly. I’ve had a very difficult time with triggering the error, but I was able to catch it and take screenshots (see below).
When the page refreshes, a GET request occurs that loads the right data, and then a POST request occurs that loads the right map. There are multiple pages, each with their own content and maps, and a user can easily navigate between pages.
i.e. When the Mordor page loads, the data for the Mordor map loads simultaneously. When I navigate to the Lothlorien page, the data for the Lothlorien map loads.
Any thoughts on what’s causing this? As I said, although this error happens rarely I do want to get to the bottom of it, in order to prevent future complications down the line.
Notes:
-
I used to have an issue to where the 403 error happened frequently (if the page was idle), but I resolved it by doing a
if resp.status === 403, window.location.reload
. That fixed the problem, but I’ve wondered if the issue I’m experiencing now is related to it and «leaking through», so to speak. -
webpack-internal
shows up in the console (see screenshots), but searching for 403 errors with webpack comes up short. -
I’m using
empty()
throughout the project, so that the old data doesn’t remain on the page.
async function loadMaps(){
let ret = axios.post( // ${location} is referenced at an earlier point, and always works
`${_Something}/something/_api/web/lists/getbytitle('Middle Earth Maps')/GetItems`,{
"query": {"__metadata": {"type":"SP.CamlQuery"}, "ViewXml": `<View><Query><Where><Eq><FieldRef Name='MiddleEarthMaps'/><Value Type='TaxonomyFieldType'>${location}</Value></Eq></Where></Query></View>`}
}, {
method: "POST",
credentials: "include",
mode: "no-cors",
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
}
}).then(resp => {
console.log(resp.status)
// in here there's other code that behaves as intended (95% of the time)
}).catch(err => {
if (err.status === 401 || err.status === 403) { // I use this for the main page of the project, and it works as intended
window.location.reload();
}
console.log("Error during loadMaps");
console.log(err);
return false;
});
return ret;
}
403 in the console
The debugger
Local in the debugger