React - GET and POST requests with axios - javascript

In my application I need to GET some data (for which I provide the native authtoken).
In the same event, however, I also need to POST a second token to be consumed by a few endpoints, for external backend api calls.
How do I POST this second token using my working code below using axios?
Should I extend Authorization bearer or simply POST Spotify Token as string data?
How so?
My code:
getData(event) {
const {token} = this.props.spotifyToken
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/endpoint`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
return axios(options)
.then((res) => {
console.log(res.data.data)
})
.catch((error) => { console.log(error); });
};

For an async await applied to your code would look something like this.
async getData(event) {
const {token} = this.props.spotifyToken
let getRes = await axios.get(`${process.env.URL}/endpoint` {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${window.localStorage.authToken}`
}
}
let postRes = await axios.post(`${process.env.URL}/endpoint` {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${window.localStorage.authToken}`
}
}
console.log(getRes.data.data);
console.log(postRes.data.data);
};

In this specific case, where a token is needed to fetch data at backend, I found that passing token at url is more suitable, like so:
#endpoint.route('/endpoint/<select>/<user_id>/<token>', methods=['GET'])
def endpoint(name, user_id, token):
# business logic
and:
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/endpoint/${select}/${userId}/${this.props.spotifyToken}`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
otherwise, backend code would run twice, for POST and GET, which is not desired in my case.

Related

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

How can use AsyncStorage in string template

//await is not working in string template is there any other way to use AsyncStorage
export const http = new HttpService(BASE_URL, {
'Content-Type': 'application/json',
Authorization: `Bearer ${await AsyncStorage.getItem('userToken')}`,
})
And without await promise is not resolved how can I fix this please help
The most straightforward way I see is to simply use a variable to first get the token from AsyncStorage and then use it in your request. Hence, your code would be something like: -
const token = await AsyncStorage.getItem('userToken');
const http = new new HttpService(BASE_URL, {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
})
You might also have to make a function, something like: -
const request = async () => {
const token = await AsyncStorage.getItem('userToken');
const http = new HttpService(BASE_URL, {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
});
}

How To Solve "Expected type object but found type string" in REST API calls? (reactjs, javascript)

I'm trying to use following Auth0 API call: https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id
const sUserMetadata = async () => {
const domain = "xxxxxxxxxxxxxxx"
try {
const accessToken = await getAccessTokenSilently({
audience: `${domain}/api/v2/`,
scope: "update:current_user_metadata",
});
const userDetailsByIdUrl = `${domain}/api/v2/users/${user.sub}`;
const metadataResponse = await fetch(userDetailsByIdUrl, {
method: 'PATCH',
headers: {
Authorization: `Bearer ${accessToken}`,
},
body: { "email_verified": true }
})
let user_metadata = await metadataResponse;
console.log(user_metadata)
} catch (e) {
console.log(e.message);
}
};
sUserMetadata().then(r => null);
I am receiving following response error:
{"statusCode":400,"error":"Bad Request","message":"Payload validation error: 'Expected type object but found type string'.","errorCode":"invalid_body"}
Obviously the Body-Tag provides it in the correct form with Bracets {} so it Should! be an Object.
I have tried:
JSON.parse()
I have tried to add Content-Type which results in a freaking "SYNTAX ERROR" because of the - in content-type which doesnt make any sense because under chrome debugger I can obviously see that there is a property called content-type: text/plain;charset=UTF-8 and I have no idea how else I am supposed to change this?
headers: {
Authorization: `Bearer ${accessToken}`,
Content-Type: 'application/json',
},
Putting Content-Type inside Apostrophes 'Content-Type' so it doesn't give a Syntax Error and then you using JSON.Stringify() at the Body-Tag part fixes the problem.
const metadataResponse = await fetch(userDetailsByIdUrl, {
method: 'PATCH',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ "user_metadata" : { "addresses": {"work_address": "100 Industrial Way"} }}),
})
PS: save me from javascript pls

How to add "Bearer" another route headers after user logged in?

I'm new to programming and I'm currently working on a small project.
I'm trying to implement some authorization using JWT.
I've watched a few videos online and found that most people have the "Bearer" + access token in their headers.
I've gone through a few posts and I found that I needed to add the authorization "Bearer" myself but I'm not quite sure how to get there.
Can I please get some help?
Here are some of my code
Login
if(response){
if(await bcrypt.compare(loginPW, response.password)){
const accessToken = jwt.sign({
email: response.email
},jwtSecret)
res.json({status: 'ok', accessToken: accessToken})
}else{
return res.json({status: 'error', error:'Invalid Credentials'})
}
}
Post request
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());
just add Authorization header with your token to request
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());
one possible way is ....on your Post requst result you can store the accessToken in localStorage
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json()).then(({accessToken})=>{
localStorage.setItem('accessToken', accessToken)
});
then retrieve it in all of your requests
const anotherRequst = await fetch('/anything',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('accessToken')}` // get it from localStorage
},
body: ... /// anything
}).then((res) => res.json());
that's the simplest way
... for more advanced techniques, try to use Axios
and you can simply set the default authorization header in all your requsts
axios.defaults.authorization = localStorage.getItem('accessToken')
then any request you make will have the accessToken in its header
Axios.post(....)
Axios.get(...)
....
You can add 'Authorization' headers within your request just like this
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());
Or if you're dealing with a big project and you have to send the token with every request then you can use Axios which allows you to add common headers with every request using only one line
axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
Docs: https://www.npmjs.com/package/axios

POST https://accounts.spotify.com/api/token 415 error when using fetch

I'm trying to make a request to get an authorization code from the spotify api using fetch but I keep getting a 415 error code. I did not have any errors when i was originally using $.ajax instead of fetch.
let client_id = '8f10fa8af1aa40c6b52073811460bf33'
let client_secret = '27a7c01912444b409a7f9a6d1f700868'
let ah = btoa(client_id + ":" + client_secret)
const getAuthToken = (searchedTerm) => {
fetch( `https://accounts.spotify.com/api/token`,
{
headers: {
'Content-Type': 'application/x-www-form-url-encoded',
'Authorization': `Basic ${ah}`
},
body: {
grant_type: 'client_credentials'
},
json: true,
method : "POST"
}
)
.then(function(response) {
authToken = response.access_token;
spotifySearch(response.access_token, searchedTerm);
})
}
See this answer on a similar post. Note that there they set 'Content-Type':'application/x-www-form-urlencoded', with no hyphen between url and encoded. I think you simply need to change
headers: {
'Content-Type': 'application/x-www-form-url-encoded',
'Authorization': `Basic ${ah}`
},
to
headers: {
'Content-Type': 'application/x-www-form-urlencoded', // no hyphen in urlencoded
'Authorization': `Basic ${ah}`
},

Categories