authorization token sending on get but not on post - javascript

SO basically i am working on axios and i am sending a token in authorization header in both get and post but i can get the token if i do get request but not if i do it with post i didnt recieve the header on post i am sharing the code here please see the issue
GET request
axios
.get(
"https://localhost:8000/user/delete/"+data+"",
{
headers: {Authorization:`Bearer ${localStorage.getItem('token')}`}
}
)
.then((response) => {
console.log(response)
if(response.data.status===200){
window.location.href='/dashboard'
}
else if(response.data.status===404){
console.log('Your token has been expired')
}
else if(response.data.status===403){
console.log('Incorrect Token')
}
else if(response.data.status===402){
console.log('Token does not matched')
}
})
}
}
POST
axios
.post(
"https://localhost:8000/user/update",
{
id:document.getElementById("id").value,
name:document.getElementById("name").value,
email:document.getElementById("email").value,
password:document.getElementById("password").value,
retype:document.getElementById("retype").value,
contact:document.getElementById("contact").value
},
{
headers: {
"Content-type": "application/json",
"Authorization":`Bearer${localStorage.getItem('token')}`
}
},
)
.then((response) => {
window.location.href='/dashboard'
})
}

Related

how can i send token to backend i n vue js

i'm trying to make payment to my backend, but each time i send the payment i get this message from my backend
{
"success": false,
"message": "No token Provided"
}
my backend requires authentication
this is my script tag
methods: {
sendTokenToServer(charge, response) {
const token = localStorage.getItem("token");
axios
.post(`http://localhost:5000/api/pay`, {
headers: {
Authorization: "Bearer" + token,
"x-access-token": token
},
totalPrice: this.getCartTotalPriceWithShipping,
})
.then(res => {
console.log(res);
});
}
}
};
</script>
when i check my dev tool i see my token
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ"
this is my backend headers
let token = req.headers["x-access-token"] || req.headers["authorization"];
please how can i go about this
your code looks fine, just create an object then add it to the url i guess your looking for something like this.. try this
methods: {
sendTokenToServer(charge, response) {
var request = {
totalPrice: this.getCartTotalPriceWithShipping,
};
const token = localStorage.getItem("token");
axios
.post(`http://localhost:5000/api/pay`,request, {
headers: {
Authorization: "Bearer" + token,
"x-access-token": token
},
})
.then(res => {
console.log(res);
});
}
}
First parameter is your url,
Second parameter is your data,
Third parameters is your config.
You can make a post request like below
axios
.post(
`http://localhost:5000/api/pay`,
data,
{
headers: {
"Authorization": `Bearer ${token}` //mind the space before your token
"Content-Type": "application/json",
"x-access-token": token,
}
}
);
NOTE: data is your request body.
e.x.
{
"firstname": "Firat",
"lastname": "Keler"
}

How to do Spotify Api Post Request using Axios

I'm trying to add a song to the playback queue using this endpoint:
const add = async () => {
try {
const url = `https://api.spotify.com/v1/me/player/queue?uri=${songUrl}&device_id=${deviceId}`
await axios.patch(url, {
headers: {
Authorization: `Bearer ${to}`
},
})
} catch (error) {
console.log(error);
}
}
I'm getting a status 401 error with a message that says no token provided. But when I console.log the token it shows up.
I haven't worked with the Spotify API yet, however, according to their docs, you need to send a POST request, not a PATCH, which is what you used.
Use axios.post() instead of axios.patch():
const add = async (songUrl, deviceId, token) => {
try {
const url = `https://api.spotify.com/v1/me/player/queue?uri=${songUrl}&device_id=${deviceId}`;
await axios.post(url, {
headers: {
Authorization: `Bearer ${token}`,
},
});
} catch (error) {
console.log(error);
}
};
The second param of your post request should be body and the third param should be headers. Also, you haven't added all the headers as mentioned in the documentation.
headers: {
Accept: 'application/json',
Authorization: 'Bearer ' + newAccessToken,
'Content-Type': 'application/json',
}
Get your access token from here: https://developer.spotify.com/console/post-queue/
If it still doesn't work try the curl method as mentioned in their docs and if it works, switch it to axios.
I had the exact same issue as you, what I realised was I was passing the header as data rather than as config. This code below should work for you as it works for me.
const add = async () => {
try {
const url = `https://api.spotify.com/v1/me/player/queue?uri=${songUrl}&device_id=${deviceId}`
await axios.post(url, null,{
headers: {
Authorization: `Bearer ${to}`
},
})
} catch (error) {
console.log(error);
}
}

Getting no authorization header value error,

Authorization Headers (bearer token) not getting adding into the api calls
Status is 401 Unautorized and headers are not getting added into the api call.
const axios = require('axios')
let token = 'eyJ0eXAiOiJOiJIUzI1NiJ9.eyJpc3MiOiJJQ00iLCJhdWQiOiJzZXNzaW9uLW1hbm'
export class classname )
async getReports ()
{
let response
try {
response = await axios.get(`https://urltogo/path`), {
headers: {
'Content-Type' : 'application/json',
Authorization : `Bearer ${token}`
}
}
const responseObj = {
url: `GET ${`https://urltogo/path`}`,
status: response.status,
data: response.data
}
if (responseObj.data.meta.count == 1) {
return responseObj.data.items[0].id
}
} catch (error) {
const errorObj = {
status: error.response?.status,
data: error.response?.data
}
throw new Error(JSON.stringify(errorObj))
}
}
}
Getting Error
"status":401,"data":{"message":"Unauthorized, **no authorization header value**"}}
data: error.response?.data
not sure what i am missing here in the code
You need to put the options as second argument of the get method, not after closing it.
response = await axios.get(`https://urltogo/path`, {
headers: {
'Content-Type' : 'application/json',
Authorization : `Bearer ${token}`
}
});
Updated the #reyno answer with bold
response = await axios.get**(**`https://urltogo/path`,{
headers: {
'Content-Type' : 'application/json',
'Authorization' : `Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ`}
} **)**;

Server returns status 403 forbidden when i send request with bearer token

I'm working with security and have a task which is bind to jwt. When i received jwt and have already saved it in LocalStorage, i was trying to send requests to the server and put this jwt in headers: Authorization: "bearer " + jwt, but server only returned status 403 forbidden. I thought, that the reason is in requests that sending earlier then token was put in header, but i've tried to put this token artificially and server also returned 403, in postman everything works well
this is my axios instance
const TOKEN_STRING = localStorage.getItem("jwt") || ""
export const axiosInstance = axios.create({
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + TOKEN_STRING,
},
})
thats how i save token in the login page
const submit = async () => {
try {
await axios
.post(baseUrl + "/api/login", loginData)
.then((res) => localStorage.setItem("jwt", res.data.jwt))
} catch (e) {
setError(e.message)
}
}
and this how i send request, which is after login page so as i think should be after localStorage receives token
const fetchData = async () => {
try {
await axiosInstance
.get(process.env.REACT_APP_BASE_BACKEND_URL + "/api/discounts")
.then((response) =>
setDiscounts(() =>
response.data.map((el, index) => ({
...el,
img: cardImages[index],
}))
)
)
} catch (e) {
setDiscountsFetchError(e.message)
}
}
useEffect(() => {
fetchData()
}, [])
i think it's enough for example but if smbd needs more info i'll give
I think you creating the axios instance way before your login call so the jwt is empty at that time.
Try the following in your fetch data request after login call, when jwt is present in local storage.
axiosInstance
.get(
process.env.REACT_APP_BASE_BACKEND_URL + "/api/discounts",
{
headers: {
Accept: "application/json",
"Content-Type": "application/json"
Authorization: 'Bearer ' + localStorage.getItem("jwt")
}
})

Axios - Sending always default header

I have an app where most of the endpoints use the same token to authenticate. So, when a user logs in I use the following:
axios.defaults.headers.common['Authorization'] = 'Bearer ' + user.access_token
But I have some endpoints that have a different Bearer token. In these cases, I'm trying this:
axios.get(`${API_BASE}/Config`, { headers: { Authorization: AuthStr } })
.then(response => {
if (response.status === 200) {
commit(HIDE_LOADING)
resolve(response.data)
}
})
Where AuthStr is being passed in as an argument and is the correct Bearer Token for this endpoint. But when I call this method, axios is sending the Bearer Token configured on axios.defaults.headers.common['Authorization'] and is ignoring my AuthStr token argument.
How can I override this?
As pointed out by #Maaz Syed Adeeb this is an axios bug. I could solve using the following code as suggested in: issue
axios.get(`${API_BASE}/EndPointThatUserAnotherToken`, getAxiosOptions(AuthStr))
.then(response => {
if (response.status === 200) {
commit(HIDE_LOADING)
resolve(response.data)
}
})
function getAxiosOptions (authToken) {
let opt = {
transformRequest: [function (data, headers) {
delete headers.common.Authorization
headers.Authorization = authToken
return data
}]
}
return opt
}

Categories