Axios bad request 400 Spotify post - axios

I am getting a bad request of 400 from Axios for trying to get the token from the Spotify API. Can someone please look at my code?. I would really appreciate someone's help.
app.get("/auth/callback", async (req, res) => {
try{
let code = req.query.code || null;
let state = req.query.state || null;
let data = qs.stringify({
grant_type: "authorization_code",
code: code,
redirect_uri: redirect_uri,
});
const response = await axios.post('https://accounts.spotify.com/api/token', data,
{
headers: {
'Authorization': `Basic ${Buffer.from(client_id + ':' + client_secret).toString('base64')}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
})
res.send(response)
}catch(error){
res.send(error)
}
})

Related

Messed data object in response with Axios

I'm making a request for getting an access_token to an auth0 API.
The request is success, but the data object containing the access token contains weird characters. The thing is that I had that object for 3-4 hours, after that it wasn't retrieved anymore. Any clues on this?
And this is the code:
(async () => {
const client = axios.create({
baseURL: 'https://my_url_to.auth0.com/oauth/token',
headers: {
'Content-Type': 'application/json'
}
});
Log.debug(body);
try {
const resp = await client.post('/', body);
console.log(JSON.stringify(resp.data));
} catch (e) {
Log.error(e);
}
})();
In v1.2.1 fixed this error.
You need to add Accept-Encoding with 'application/json' in axios header.
The default of axios is gzip.
This code will be works
(async () => {
const client = axios.create({
baseURL: 'https://my_url_to.auth0.com/oauth/token',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'application/json'
}
});
Log.debug(body);
try {
const resp = await client.post('/', body);
console.log(JSON.stringify(resp.data));
} catch (e) {
Log.error(e);
}
})();

Connecting to WhatsApp API using axios.post using TypeScript

I just started using the WhatsApp Cloud API.
I took the example that was provided on glitch as a reference but there are things that are different since I'm taking the serverless approach.
As seen in glitch's example, it used axios(config) method and I tried it out and it worked fine after minor changes but when I tried axios.post() method I keep on getting the following error:
AxiosError: Request failed with status code 400
The axios(config) method (Which works)
await axios({
method: "POST", // Required, HTTP method, a string, e.g. POST, GET
url:"https://graph.facebook.com/{{Version}}/{{Phone-Number-ID}}/messages?access_token={{Token}}",
data: {
messaging_product: "whatsapp",
recipient_type: "individual",
to: {{Recipient-Phone-Number}},
text: {body: "Welcome back"},
},
headers: {"Content-Type": "application/json"},
});
The axios.post() method (Which doesn't works)
let url = "https://graph.facebook.com/{{Version}}/{{Phone-Number-ID}}/messages"
let payload = {
messaging_product: "whatsapp",
recipient_type: "individual",
to: {{Recipient-Phone-Number}},
text: {body: "Welcome back my friend"},
}
let headers = {"Content-Type": "application/json", "Authorization":"Bearer {{token}}"
}
let params = {}
try
{
const resp = await axios.post(url, {payload}, {headers, params});
log("POST RESP",resp)
}
catch(error)
{
throw error;
}
Try below code.
let url = 'https://graph.facebook.com/<Version>/<Your Phone number ID>/messages';
let payload = {
'messaging_product': 'whatsapp',
'recipient_type': 'individual',
'to': '123456789012',//Recipient Phone Number
'type': 'text',
'text': {
'body': 'Welcome back my friend'
}
};
let headers = {
'Authorization': 'Bearer <Your Temporary access token>',
'Content-Type': 'application/json'
};
axios.post(url, payload, {
headers: headers
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

axios post request fails with bad request

I try to do a simple post request with axios.
My code snippet:
const getOauthToken = async () => {
try {
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-ProxyPass' : '...',
}
const data = {
...
}
return await axios.post('/oauth2/token', data, {headers: headers});
} catch (error) {
throw new Error(`Unable to get an authentication token. Reason ${error}`);
}
};
This call fails with http 400. When I set the headers as default with
axios.defaults.headers.post['X-ProxyPass'] = '...';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
then it works.
Found the solution in the documentation of axios.
If I use "application/x-www-form-urlencoded", I have to use querystring to serialize in the needed format.
return await axios.post('/oauth2/token', querystring.stringify(data), {headers: headers});
But why it works, when I set the headers as default headers i still mysterious.

Axios OPTIONS instead of POST Request. Express Rest API (CORS)

Im trying to use Axios (and VueJs) to make a Cross Origin POST Request to my Rest Api (running on localhost). Instead of doing a POST request, it actually does a OPTIONS request to my Rest Api. This circumvents a middleware function that checks for a token and return 403.
This is the login function
router.post('/login', (req, res) => {
User.authUser(req.body, (err, user) => {
var passwordIsValid = bcrypt.compareSync(req.body.password, user.password);
if (err) throw err;
if (!user) {
res.json({ success: false, message: 'User nicht gefunden' });
} else if (user) {
if (!passwordIsValid) {
res.json({ success: false, message: 'Falsches Passwort' });
} else {
const payload = {
admin: user.admin
};
var token = jwt.sign(payload, config.secret, {
expiresIn: 86400
});
res.json({success: true, message: 'Token!', token: token});
}
}
})
});
How can I get Axios to make a proper POST request? I tried this hack, because I first thought the OPTIONS Request was just a preflight, but there is no request after I return 200 (or 204)
CORS Middleware:
app.use(function(req, res, next) { //set Response Headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
if ('OPTIONS' == req.method) {
res.send(204);
}
else {
next();
}
});
Axios will sometimes send an OPTIONS request as part of a cors preflight if it doesn't know the Content-Type of a request.
You can get explicitly specify the Content-Type when you build the request, and then it should send your POST request as expected.
Instead of
axios.post(url, params), try:
axios.post(url, params, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})

Posting Images using formData to a Django Rest API

I have a Django Rest API backend and am using a React Native Front End. I wanted to save an image to the rest API.
The POST method used is as follows:
async saveUserData() {
let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN);
var formData = new FormData();
formData.append("bio",this.state.bio);
formData.append("website",this.state.website);
formData.append("phoneno",this.state.phoneno);
formData.append("gender",this.state.gender);
formData.append("avatar",this.state.avatar.uri);
try {
let response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': ' Token '+accessToken,
},
body: formData
});
let responseJson = await response.text();
if(response.status>=200&&response.status<300){
console.log("POST Completed");
}else{
let error=responseJson;
console.log(error);
throw error;
}
return responseJson;
} catch(error) {
return error;
console.error(error);
}
}
I get the following error
{"avatar":["The submitted data was not a file. Check the encoding type on the form."]}
I have also tried this.state.avatar.data and tried to post it but I end up getting the same error. I know that the file upload works fine as I can do it properly from the REST Autogenerated form. What seems to be the problem in the image I am posting?
Here is how you can do it:
var formData = new FormData();
formData.append('avatar', {uri: this.state.avatar.uri, name: 'yourname.jpg', type: 'image/jpg'});
let response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': ' Token '+accessToken,
},
body: formData
});