Axios is sending the wrong token - reactjs

In React, this is working:
let token = localStorage.getItem("token");
axios
.post(
`http://localhost/api`,
(data: data),
{
crossdomain: true,
},
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Credentials": "true"
},
}
)
Everything is ok. It gives success.
But in React Native (AsyncStorage), it gives wrong token error (403):
let token = AsyncStorage.getItem("token");
axios
.post(
`http://localhost/api`,
(data: data),
{
crossdomain: true,
},
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Credentials": "true"
},
}
)
In console.log(token), everything seems great. I can see my token. It also works well in Postman.

According to the docs:
Returns:
Promise resolving with a string value, if entry exists for given key,
or null otherwise.
Promise can also be rejected in case of underlying storage error.
Since it returns a Promise, you should get the token using .then() or async/await:
async function doRequest() {
let token = await AsyncStorage.getItem("token");
// do request
}

I want to know whoever sees this post in the future that Axios did not send my headers in React-Native. In such a case, maybe you should try fetch.
#Rafael's answer was also great.
fetch("http://localhost/api", {
method: "post",
headers: new Headers({
"x-auth-token": `${token}`,
"Content-Type": "application/json",
}),
body: {
body
},
});

Related

React-Axios Getting error 401 (Unauthorized) for PUT Method

I have gone through many posts and tested most of them but I still get this error.
It's interesting that I don't get this error for the get method. I get this error only for put method.
thanks to everyone
axios error 401 (Unauthorized)
axios
.put("/api/v1/Profile", {
fullName: userName,
gender: Number(userGender),
phoneNumber: userNumber,
headers: {
Accept: 'application/json',
"Content-Type": "application/json; charset=UTF-8",
Authorization: `Token ${userToken}`,
},
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
There is no error for the get method, but it gives an error for the put method
I tested it with Postman and it works without errors
There is something wrong with your Authorization header. You're using the right syntax (see MDN):
Authorization: <auth-scheme> <authorization-parameters>
Given userToken is your <authorization-parameters>. The problem comes from the <auth-scheme> for which you used Token: this is not a valid scheme according to the list maintained by IANA.
Hard to be sure without much information, but I guess what you want is:
Authorization: `Bearer ${userToken}`,
My problem was solved with this format:
axios({
method: 'put',
url: 'api/v1/Profile/',
data: {
fullName: userName,
gender: Number(userGender),
phoneNumber: '',
},
headers: {
'Content-Type': 'application/json; charset=UTF-8',
Authorization: `Bearer ${userToken}`,
},
}).then((response) => {
console.log(response);
});

axios https call now working, why it always takes to https?

i am working on react axios, i run the axios call, you can see i setup the http api call, but when i run the code, it call https api, can anyone please help me why it is doing that ? any help will be really appreciated.
await axios({
method: 'Post',
//url: `${helper.ApiUrl}auth/signin`,
url : 'http://xx.xx.xx.xx/',
responseType: 'json',
// withCredentials: true,
// credentials: 'same-origin',
headers: {
"Access-Control-Allow-Origin": "*",
'Access-Control-Allow-Credentials': 'true',
"Access-Control-Allow-Headers": "Content-Type, Authorization",
mode: 'no-cors',
},
data: {
'email': email,
'password': password,
}
}).then((response) => {
res = response
});

Make user join discord guild with guilds.join request

Code:
let response = await fetch(
`https://discord.com/api/guilds/877414872068001853/members/[user id]`,
{
method: 'PUT',
access_token: `Bearer [user access code]`,
headers: {
"Authorization": `Bot [bot token]`,
"Content-Type": "application/json"
}
}
);
console.log(response);
The bot is in the server that I want the user to join
The guilds.join oauth scope is set
Error:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null },
[Symbol(Response internals)]: {
url: 'https://discord.com/api/guilds/877414872068001853/members/522503261941661727',
status: 400,
statusText: 'Bad Request',
headers: [Headers],
counter: 0
}
}
Thanks to #user15517071
I had the access_token not in the body, and also the "access token" i was using was just the redirect token from discord oauth so i needed to use the actual access Token discord provides you after getting the users details, and it works.
{
method: 'PUT',
body: JSON.stringify({
access_token: `Bearer User_AccessToken`,
}),
headers: {
"Authorization": `Bot Bot_Token`,
"Content-Type": "application/json"
}
};

Possible bug with axios default headers and transformRequest

This bug has caused serious trouble for me. Finally i was able to get to the root of it.
(A similar version of bug has been reported in GitHub but it has been marked as fixed)
Axios will fail to set the correct header type and goes for default header type when transformRequest is used.
I am not sure what exactly is causing this issue but here is a quick way of reproducing the issue.
Here i have defined an axiosInstance
const axiosInstance = axios.create({
baseURL: baseURL,
timeout: 360000,
transformRequest: [
function (data, headers) {
const accessToken = window.localStorage.getItem('access_token');
if (accessToken) {
headers['Authorization'] = `Bearer ${accessToken}`;
} else {
delete headers.Authorization;
}
return JSON.stringify(data);
},
],
headers: {
'Content-Type': 'application/json',
accept: 'application/json',
Authorization: `Bearer ${window.localStorage.getItem('access_token')}`,
},
});
Now i have to send multipart/form-data.
let formData = new FormData();
formData.append('profile_pic', file, file.name);
axiosInstance
.put('http://127.0.0.1:8000/users/profile-pic-upload/', formData)
.then((res) => console.log(res))
.catch((err) => alert(err));
Since formData is contains image here i expected the axios to override the default header's content-type from 'application/json' to 'multipart/form-data'. But it turns out the content-type in the sent request packet is still 'application/json'.
But when i comment out the transformRequest section. Surprisingly it correctly sets the content-type to 'multipart/form-data'.
const axiosInstance = axios.create({
baseURL: baseURL,
timeout: 360000,
transformRequest: [
// function (data, headers) {
// const accessToken = window.localStorage.getItem('access_token');
// if (accessToken) {
// headers['Authorization'] = `Bearer ${accessToken}`;
// } else {
// delete headers.Authorization;
// }
// return JSON.stringify(data);
// },
],
headers: {
'Content-Type': 'application/json',
accept: 'application/json',
Authorization: `Bearer ${window.localStorage.getItem('access_token')}`,
},
});
I am using axios 0.20 (i noted that axios 0.21 also has same issue as well).
I found a similar issue on Github it says it has been fixed in axios 0.20
https://github.com/axios/axios/issues/2623
Please confirm that whether this is an existing bug or am i doing something wrong.
I have written more detailed description in my previous stackoverflow post.
AxiosInstance setting default type to "application/x-www-form-urlencoded" instead of expected "multipart/form-data"

spotify api returns 400

I am implementing the Search function using spotify api.
However, if you request get to api now, 400 will be returned.
I want you to help me with this.
axios({
headers: {
"Authorization": `Bearer ${token}`
},
method: 'GET',
url: 'https://api.spotify.com/v1/search',
qs: {
q: value,
type: 'album',
},
}).then((res) => {
console.log(res);
}).catch(err => {
console.log(err);
})
const options = {
method: 'GET',
url: `https://api.spotify.com/v1/search?q=${value}&type=album`,
headers: {
'Authorization': `Bearer ${token}`,
"Accept": "application/json",
"Content-Type": "application/json",
}
}
axios(options).then((res)=>console.log(res))
.catch(err=>console.error(err))

Resources