415 coming back from requesting a token Spotify API - api

I'm trying to receive a token from Spotify api. Unfortunately I keep on receiving 415. Could you help me and let me know what am I doing wrong?
const axios = require('axios');
const getToken = (code) => {
return axios({
method: 'post',
url:'https://accounts.spotify.com/api/token',
form: {
code,
grant_type :'authorization_code',
redirect_uri: process.env.SPOTIFY_REDIRECT
},
headers: {
'Authorization': 'Basic ' + (new Buffer(process.env.SPOTIFY_ID + ':' + process.env.SPOTIFY_SECRET).toString('base64')),
'Content-Type': 'application/json'
}
}).then(token => {
return token;
}).catch(e=> {
console.log(e);
return e.response;
});
};
module.exports = {
getToken
};

415 error code is related to problem with wrong content type or content encoding, (https://httpstatuses.com/415)
I do not know axios but please take a look on the example on spotify github https://github.com/spotify/web-api-auth-examples/blob/master/authorization_code/app.js#L74
According to this issue on github (https://github.com/spotify/web-api/issues/321), try to use content-type 'Content-Type': 'application/x-www-form-urlencoded'
There is example withs axios
axios({
url: "https://accounts.spotify.com/api/token",
method: "post",
params: {
grant_type: "client_credentials"
},
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
auth: {
username: "YOUR-CLIENT-ID",
password: "YOUR-CLIENT-SECRET"
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
});

It works!!!
What I've done was:
- change Content-Type for 'application/x-www-form-urlencoded'
- client_id and client_secret were taken from header and posted before grant_type in body
- changed 'data' to 'params'
const axios = require('axios');
const getToken = (code) => {
return axios({
method: 'post',
url:'https://accounts.spotify.com/api/token',
params: {
client_id: process.env.SPOTIFY_ID,
client_secret: process.env.SPOTIFY_SECRET,
code,
grant_type :'authorization_code',
redirect_uri: process.env.SPOTIFY_REDIRECT
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(token => {
return token;
}).catch(e=> {
return e.response.data;
});
};
And it resulted with a beautiful looking token \m/

After spending one hour trying to figure out how to get the token, I came up with this answer! :)
const axios = require('axios');
const express = require('express');
const app = express();
const client_id= 'YOURCLIENTID';
const client_secret = 'YOURCLIENTSECRET';
app.get('/api/token', (req, res) => {
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
headers: {
'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64')),
'Content-Type': 'application/x-www-form-urlencoded'
},
params: {
grant_type: 'client_credentials'
},
json: true,
})
.then(body => {
res.send(body.data.access_token);
})
.catch(e => {
console.log(e.response.data);
});
});
app.listen(3000, () => {
console.log('Server Listening on port 3000');
});

If you making API call from client side (browser), try this solution:
getTokken() {
const urlSpotify = "https://accounts.spotify.com/api/token";
axios({
method: "post",
url: urlSpotify,
data: "grant_type=client_credentials",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
auth: {
username: process.env.REACT_APP_SPTID_KEY, // User ID
password: process.env.REACT_APP_SPCS_KEY, // User Secret
},
})
.then((response) => {
console.log(response);
})
.catch((err) => console.log(err));
}

Related

Problem with API of Twitch with Axios GET POST

i got problem with codes.
axios({
method: 'post',
url: 'https://id.twitch.tv/oauth2/token',
body: {
client_id: 'a',
client_secret: 'Bearer b',
grant_type: 'client_credentials',}
}).then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
})
and result is :
data: { status: 400, message: 'missing client id' }
but this way works fine if i put them in url :
url: 'https://id.twitch.tv/oauth2/token?client_id=a&client_secret=b&grant_type=client_credentials',
what is my problem?
also can u give me an example for axios.get ? with :
url: 'https://api.twitch.tv/helix/games/top'
headers: {
client_id: 'a',
Authorization: 'Bearer b',
}
For axios you need to be sending as data not body
And then construct/send a FormData
So for example
axios({
method: "post",
url: "myurl",
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
See also: axios post request to send form data
and: https://github.com/axios/axios/issues/318
Using body will get mixed results as the library (axios) won't know how to encode the data being sent
Personally myself I'm using got over axios so I send
got({
url: "https://id.twitch.tv/oauth2/token",
method: "POST",
headers: {
"Accept": "application/json"
},
form: {
client_id: config.client_id,
client_secret: config.client_secret,
grant_type: "client_credentials"
},
responseType: "json"
})
.then(resp => {
//SNIP
apparently the API receives the parameters via URL so it's interesting to pass them as url too.
Ex: axios({
method: 'post',
url: 'https://id.twitch.tv/oauth2/token?client_id=${variable.a}&client_secret=${variable.b}...

Axios React upload jpg

I have photo file taken with ImagePicker, and I need upload it to server, using axios, and I need send type as a string with this photo.
My code here
const axiosMultipart = axios.create({
timeout: 3000,
baseURL: BASE_URL,
headers: {
'Content-Type': 'multipart/form-data'
}
})
uploadDocs(token,type,photo){
let data = new FormData();
data.append('photo', photo);
data.append('type', type);
return axiosMultipart
.post(
`uploadDocs`,
{data},
{
headers: {
Authorization: token,
},
}
)
.then((response) => {
return response.data;
})
.catch((error) => console.log("uploadDocs: " + error));
};
Server response is error_code 400
What is wrong here?
Also I have code on php with a working request
Try With Below Code,
var photo = {
uri: file,
type: 'image/jpeg',
name: 'photo.jpg',
};
var FormData = require('form-data');
var form = new FormData();
form.append('photo', photo);
form.append('filetype', filetype);
axios({
method: 'post',
headers: {
"Accept": "application/json",
'Content-Type': 'multipart/form-data',
"Authorization": authData
},
data: form,
url: `${base_url}`,
}).then(async (result) => {
console.log("uploadFile detail Response===>", result);
}).catch((error) => {
console.log("uploadFile detail error===>", error);
callback({ status: false, result: error })
});

Pass Fetch Request to another Fetch Request in React Native

I'm fairly new to react native so be gentle please. I have a double fetch request inside componentDidMount which works as expected:
componentDidMount() {
const auth = new Buffer('username:HASHGOESHERE');
const token = auth.toString('base64');
const authHeader = 'Basic ' + token;
fetch('https://example.com/api-connect/get-token.php', {
method: 'POST',
headers: {
'Authorization': authHeader,
'Content-Type': 'application/json'
},
}).then((response) => response.json())
.then((responseText) => {
if (responseText.status.status === 'success'){
fetch('https://example.com/api-connect/send-request.php?action=get_faq', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + responseText.payload.access_token,
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((responseData) => {
this.setState({
isLoading: false,
faqs: responseData.payload.faqs,
});
})
}else{
alert('Something has gone wrong.');
}
})
}
I have to use the get token fetch request everytime i need to make a fetch request throughout my app. I was wondering if there is a way to set up the get token fetch request (maybe in a different file) so i can call/import it when i need, then pass a second fetch to it somehow rather than having to write all my fetch requests as above.
Hopefully what i'm asking makes sense - i can provide more code if needed.
Thanks in advance
Try is with await:
React Component
async componentDidMount() {
const auth = new Buffer('username:HASHGOESHERE');
const token = auth.toString('base64');
const authHeader = 'Basic ' + token;
const tokenRequest = await getToken();
if (tokenRequest.status.status === 'success'){
const response2 = await fetch('https://example.com/api-connect/send-request.php?action=get_faq', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + tokenRequest.payload.access_token,
'Content-Type': 'application/json',
},
})
const responseData = await response2.json();
this.setState({
isLoading: false,
faqs: responseData.payload.faqs,
});
}else{
alert('Something has gone wrong.');
}
}
Somefile.js
export const getToken = async () => {
const response = await fetch('https://example.com/api-connect/get-token.php', {
method: 'POST',
headers: {
'Authorization': authHeader,
'Content-Type': 'application/json'
},
})
const responseText = await response.json();
return responseText
}
Don't forget to import 'Somefile.js' to the react component.

Can't get a .post with 'Content-Type': 'multipart/form-data' to work Axios React Native

i'm trying to upload FormData which include text ,image,pdf etc
I am using axios.
Axios Call
const sellerRegister = params => {
console.log(params);
return dispatch => {
dispatch(servicePending());
return axios
.post(`${BaseUrl}/seller/register`, params, {
headers: {
Accept: "application/json",
"Content-type": `multipart/form-data; boundary=${params._boundary}`
}
})
.then(res => {
return dispatch(sellerRegisterSuccess(res));
})
.catch(err => {
return dispatch(serviceError(err.message));
});
};
};
Params in FormData
ServiceError
Provide solutions of this error. and also guide me am i doing this in right way or not ?
Thanks
Using the latest version of Axios, you make an HTTP request with 'Content-Type': 'multipart/form-data' in the header as follows:
const formData = new FormData();
formData.append('action', 'ADD');
formData.append('param', 0);
formData.append('secondParam', 0);
formData.append('file', new Blob(['test payload'], { type: 'text/csv' }));
axios({
url: 'http://your_host/api/auth_user',
method: 'POST',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
})
use url instead of uri.
or
You can do simply:
axios.defaults.headers.common['Content-Type'] = 'multipart/form-data;
boundary=someArbitraryUniqueString';

fetch post always pass null to the parameters

There's a fetch post with "userid" as a parameter. I've tested the url and parameter in native android, it works there but here it doesn't take the parameter. It always sends the null value to "userid" parameter. Am I doing smthing wrong here?
fetch('http://zzz.com/zzz/api/battery/gpswithbattery', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
userid: '404',
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
//return responseJson.message;
this.setState({
data: responseJson.message
})
})
.catch((error) => {
console.error(error);
});
I see no mistake you are doing here, and start using es7 syntax, as that'll be even cleaner and easy to find mistakes,
pro-tip: use prettier that'll make to look your code better.
const method = async () => {
const reponse = await fetch("http://zzz.com/zzz/api/battery/gpswithbattery", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
userid: "404"
})
});
const responseJson = await response.json();
this.setState({ data: responseJson.message });
};