401 error when performing GET request w/ axios - javascript

I can view my JSON data in my browser but not in my console. I'm not super familiar with axios, but I think the problem is with the url (see snippet below). That, or I'm missing something within axios.get {.
Any thoughts?
server.js:
axios.get("https://handshake.[redacted].com/HandshakeWebServices/Odata/Odata.ashx/HS[redacted]?hsf=#UserName=%27[redacted]%27&$select=PreferredName,Initials,JobTitle,Office", {
crossDomain: true,
method: "GET",
credentials: "include",
mode: "no-cors",
headers: {
"Accept": "application/json; odata=verbose"
}
})
.then(function(res){
console.log(res.data);
})
.catch(function(e){
console.log(e);
})
console:
GET https://handshake.[redacted].com/HandshakeWebServices/Odata/Odata.ashx/HS[redacted]?hsf=#UserName=[redacted]&$select=PreferredName...etc 401 (Unauthorized)
server.js?1d69:18 Error: Request failed with status code 401
at createError (createError.js?2d83:16)
at settle (settle.js?467f:18)
at XMLHttpRequest.handleLoad (xhr.js?b50d:77)

The site is returning a 401 which means you are not authorised to access the URL.
Normally, this means you need to send credentials.
Now, you've said credentials: "include", but that's a property recognised by fetch, not axios. The axios equivalent is withCredentials: true, so set that instead.
You've also said mode: "no-cors", which is another property recognised by fetch, not axios. You don't want it anyway. Sending credentials requires permission via CORS, so by rejecting CORS, reject the possibility to get permission to send the credentials.
Remove that property.

Related

Request failed with status code 403 - magiceden api with axios

Please help me, I'm so stuck on this problem: I'm making a request magiceden.io API with Axios on Javascript and the request is not working (Request failed with status code 403).
My URL request: https://api-mainnet.magiceden.io/new_collections
My code:
axios.get("https://api-mainnet.magiceden.io/new_collections", {
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"User-Agent": "Mozilla/5.0",
},
}).then((res) => {
console.log(res.data);
}).catch((err) => {
console.log(err.message);
});
Status 403 means that the request is a forbidden access. It is probably because MagicEden now uses Cloudflare protection which restricts access. You can try changing your request headers which can bypass the cloudflare protection.

React Native - Request with URL that includes credentials

So I have to make requests to various urls with different domains which contains credentials
I've successfully managed to send one like this:
const resp = await fetch(`my-url-here`, {
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'Authorization': `Basic ${base64.encode(my-key-here)}`
},
body: JSON.stringify(data)
})
However this works only for one domain while on the other I keep getting
[TypeError: Network request failed] on Android
[SyntaxError: JSON Parse error: Unexpected identifier "undefined"] on iOS (while executing the .json() method; I think the request is successful but with an empty response)
Every call on these domains work correctly using PostMan/ThunderClient
Any idea how to solve this?
Please share how you are processing response seems like request works fine but somehow there is an error while parsing the data into JSON.
invalid data contains in response which is not able to parse into JSON.

Make post request from js to django rest framework

I have a DFR api endpoint:
url = http://127.0.0.1:8000/x/y/
Url of the page running JS code: http://127.0.0.1:8000/x/z/1/
I have logged in as User1 in my browser.
POST request - from DRF browser api - good.
GET request - from javascript - good.
POST request - from javascript - 403 error.
So perhaps I dont know how to make an authenticated ajax request from JS. When I do the same request from browser api, may be the browser takes care of authentication.
My current js code:
axios({
method: 'post',
baseURL: window.location.origin,
url: '/x/y/',
// adding auth header also gives same 403 error for post request
// headers: {
// Authorization: 'Token e77b8ca898b51cde72dcf2aa2c385942d771e972'
// },
data: {
name: 'xyz'
},
responseType: 'json',
})
.then(function (response) {
console.log(' success');
})
.catch(function (error) {
console.log(' error=', error.message);
});
If you are on chrome browser, go in console ctrl+shift+j and then go in network.
When a post request is made, we can see the error message in this network tab.
My post request had following error:
"CSRF Failed: CSRF token missing or incorrect."
To add csrf token on axios ajax request put following lines of code at beginning of your js file:
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
Are you appending the CSRF token in your request,CSRF can cause 403 errors.Try appending csrf token in request headers

sending cookies with ajax request via fetch api

In a nodeJs app, i am sending multipart/form-data to the server via ajax request. I am also using csurf package to guard against csrf attacks
Problem
When i submit my form without ajax request, everything works fine but when i submit my form using ajax request, i get invalid csrf token error on the server.
As far as i have understood the cause of this error, its because of cookies not sent with the request.
To send the cookies with ajax request, i set credentials: 'same-origin' in the post request made via fetch api but that didn't fix the issue. I also tried setting credentials: 'include' but that didn't make any difference.
Question
Is my understanding correct that this issue is because of cookies not being sent with ajax request and how can i fix this issue?
Code
let response = await fetch(requestUrl, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'multiplart/form-data'
},
body: new URLSearchParams(form)
});
When using fetch()/AJAX with csurf, you need to pass the CSRF token as a request header:
// Read the CSRF token from a hidden input in the form
const token = document.querySelector('input[name="csrf-token"]').value;
// POST using the Fetch API
fetch('/<route.name>', {
headers: {
// pass the csrf token as a header
'CSRF-Token': token
},
method: 'POST',
body: {
...
}
});

Post request using axios fails with "Response for preflight is invalid" error

I made the following post request to a 3rd party api, from my web frontend, using axios, but it couldn't go through.
Axios({
method: 'post',
url: 'https://some.website.com/oauth/token',
data: {
client_secret: 'revmisodtoire43-00j232onfkdl',
code: '54728349765905473289',
grant_type: 'authorization_code'
}
})
.then(res => {
console.log('client info: ', res);
});
The error says:Failed to load https://some.website.com/oauth/token: Response for preflight is invalid, and then network error.
When I made the same request via curl, it went through with no problem.
I know this is CORS related, but am not sure what to do with it. Any suggestions?
Check whether content-type is being added in the header's, if not try adding this
'Access-Control-Allow-Origin': '*' in the request headers

Categories

Resources