Reputation: 83
Following code works fine:
request({
url: 'https://xxxxxxx/oauth/token',
method: 'POST',
auth: {
user: 'clientId',
pass: 'clientSecret'
},
form: {
'grant_type': 'client_credentials'
}
}, function(err, res) {
var json = JSON.parse(res.body);
console.log("Access Token:", json.access_token);
});
However, when I try and replicate this using Axios (as request is now deprecated) i keep getting a 401
axios.request({
url: 'https://xxxxxxx/oauth/token',
method: 'POST',
auth: {
username: 'clientId',
password: 'clientSecret',
},
headers: {
Accept: 'application/json','Content-Type':'application/x-www-form-urlencoded',
},
data: {
grant_type: 'client_credentials',
},
}).then(function(res) {
console.log(res);
}).catch(function(err) {
console.log("error = " + err);
});
i.e. catch picks up the error response 401
Any ideas on how to code the successful 'request' into axios ??
Upvotes: 2
Views: 8355
Reputation: 83
Solution suggested above sorted the problem. Solution looks like:
const qs = require('querystring');
const data = { 'grant_type': 'client_credentials'};
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
auth:{
username: 'clientId',
password: 'clientSecret',
},
data: qs.stringify(data),
url: 'https://xxxxxxxxx/oauth/token',
}
axios.request(options).then(function(res) {
console.log(res);
}).catch(function(err) {
console.log("error = " + err);
});
Upvotes: 5
Reputation: 22768
By default axios
sends data in JSON format. To send form data you need to use URLSearchParams
or qs.stringify
.
See Using application/x-www-form-urlencoded format
Upvotes: 2