how can i send token to backend i n vue js - javascript

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"
}

Related

I am not able to send JWT token in headers in react.js

I am trying to send the JWT token in the headers in the Axios API call but in react.js I am not able to send it. I have tried some ways to send it in the header but on the backend, I am not able to get it. And If send the same token on postman then the backend is able to extract the token from the headers.
const token = window.localStorage.getItem("token");
console.log("token",token) // token
const apiHeaders = {
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json, text/plain, */*",
"token": `${token}`,
},
};
const result = await Axios.get(
`${process.env.REACT_APP_BASE_URL}/api/student/AllProjects`,
{
withCredentials: true,
headers: apiHeaders,
}
);
I have also tried sending token as
token: `${token}`
or
token: token
I don't know what I am doing wrong here?
I think your problem is that you have headers twice:
const apiHeaders = { headers: { ... } }
So apiHeaders is an object with a headers field.
When you use that in the get call, that gets expanded to what is effectively:
const result = await Axios.get(
`${process.env.REACT_APP_BASE_URL}/api/student/AllProjects`,
{
// You probably don't need to do this! withCredentials: true,
headers: {
headers: {
token: token
}
},
}
);
BTW, it would be normal to pass that as a "bearer token" in the authorization header:
headers: {
Authorization: `Bearer ${token}`
}
Also, you probably don't need the withCredentials when you post the token in a header.

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")
}
})

"grant_type parameter is missing": Spotify API PKCE OAuth Flow Troubles

I'm developing a React app that uses the Spotify API I can't figure out why I'm getting this error when trying to get an access token with the API's PKCE OAuth flow.
{
error: "unsupported_grant_type",
error_description: "grant_type parameter is missing"
}
I'm following the directions from the guide exactly and I'm able to obtain an auth code just fine. Here's my call trying to get the token.
let res = await axios.post("https://accounts.spotify.com/api/token", {}, {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
params: {
"grant_type": "authorization_code",
"code": data.code,
"redirect_uri": redirectUri,
"code_verifier": verifier,
"client_id": clientId
}
}).catch(err => console.error(err));
I've tried passing the params in the body of the post request and as url params and both produce the same results. As you can see, I'm clearly providing a grant_type and I'm using the value that the guide said to use.
I've tried every method I was able to find on the internet, nothing seemed to be working, but after a few hours, this succeeded:
const headers = {
Authorization:
'Basic ' +
new Buffer(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64'),
}
const { data } = await axios.post(
'https://accounts.spotify.com/api/token',
'grant_type=client_credentials',
headers: { headers },
)
this.token = data.access_token
After this, you can simply use any endpoint as seen in the Spotify API examples.
Use querystring npm package to parse the data since we're using application/x-www-form-urlencoded in the header
And change the grant_type to grant_type: "client_credentials"
var querystring = require('querystring');
const headers = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
};
let data = {
grant_type: "client_credentials",
code: data.code,
redirectUri: "http://localhost:8000/callback",
client_id: your_client_id,
client_secret: your_client_secret,
};
we use query.stringify() for the data because the content type is application/x-www-form-urlencoded also don't use params since its a post request
axios
.post(
"https://accounts.spotify.com/api/token",
querystring.stringify(data),
headers
)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
This works for me:
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
'Basic ' +
Buffer.from(this.clientId + ':' + this.clientSecret).toString('base64'),
};
this.http.post(
'https://accounts.spotify.com/api/token',
'grant_type=client_credentials',
{ headers },
).subscribe(data => {
console.log(data);
});
I have the same issue, and it's resolved with stringfying request body data
const requestAccessToken = ({
code,
grantType = "authorization_code",
redirectUri = `${APP_BASE_URL}/callback`,
}) => {
const data = qs.stringify({ //query-string library
code,
grant_type: "client_credentials",
redirect_uri: redirectUri,
});
return axios.post(
[SPOTIFY_ACCOUNTS_BASE_URL, SPOTIFY_ACCOUNTS_TOKEN_URI].join(""),
data,
{
headers: {
Authorization: `Basic ${Buffer.from(
`${SPOTIFY_CLIENT_ID}:${SPOTIFY_CLIENT_SECRET}`,
).toString("base64")}`,
"Content-Type": "application/x-www-form-urlencoded",
},
},
);
};
Have you traced the message and verified that the request body is definitely as expected? Your OAuth fields look totally correct so I suspect this could just be an axios syntax issue.
I could be wrong but should the 'params' field be called 'data' instead, as in this class of mine.

Categories