Следующий код работает нормально:
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.info("Access Token:", json.access_token);
});
Однако, когда я пытаюсь воспроизвести это с помощью Axios (поскольку запрос теперь устарел), я продолжаю получать 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.info(res);
}).catch(function(err) {
console.info("error = " + err);
});
т.е. catch получает ответ об ошибке 401
Любые идеи о том, как закодировать успешный «запрос» в axios?
По умолчанию axios
отправляет данные в формате JSON. Чтобы отправить данные формы, вам нужно использовать URLSearchParams
или qs.stringify
.
Решение, предложенное выше, устранило проблему. Решение выглядит так:
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.info(res);
}).catch(function(err) {
console.info("error = " + err);
});