I'm trying to write a Post method with Axios in NodeJS.
I have following things to pass as param in post method
url = http:/xyz/oauthToken
header 'authorization: Basic kdbvkjhdkhdskhjkjkv='\
header 'cache-control:no-cache'
header 'content-type: application/x-www-form-urlencoded'
data 'grant_type=password&username=user123&password=password123'
As I tried with following code but new to Axioz not sure how can exactly implement the header with grant type of body response.
var config = {
headers: {'Authorization': "bearer " + token}
};
var bodyParameters = {
data 'grant_type=password&username=user123&password=password123'
}
Axios.post(
'http:/xyz/oauthToken',
bodyParameters,
config
).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
});
Any help/suggestion would be appreciated :-)
Currently, axios does not make it convenient to use form-encoded data; it's mostly optimized toward JSON. It's possible, though, as documented here.
const querystring = require('querystring');
const body = querystring.stringify({
grant_type: 'password',
username: 'user123',
password: 'password123'
});
axios.post('http:/xyz/oauthToken', body, {
headers: {
authorization: `bearer ${token}`,
'content-type': 'application/x-www-form-urlencoded'
}
});
Related
I am currently stucked on making post requests to pinterest api. While I feel my code is working well, I keep getting back "Invalid Request Body" from the pinterest api.
Based on the documentation on their site, here is how they said the request should be made:
curl -X POST https://api.pinterest.com/v5/oauth/token --header "Authorization: Basic {base64 encoded string made of client_id:client_secret}" --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'grant_type=authorization_code' --data-urlencode 'code={YOUR_CODE}' --data-urlencode 'redirect_uri=http://localhost/'
Here is how I made the request using Axios from my ExpressJS application:
const redirectUrl = process.env.PINTEREST_OAUTH_CALLBACK_URL;
const clientId = process.env.PINTEREST_APP_ID;
const clientSecret = process.env.PINTEREST_APP_SECRET;
let url = 'https://api.pinterest.com/v5/oauth/token';
let accessTokenRequestBody = {
code: encodeURIComponent(code), //code is defined at the top as received from pinterest
grant_type: encodeURIComponent("authorization_code"),
redirect_uri: encodeURIComponent(redirectUrl)
}
console.log(`RequestBody =${JSON.stringify(accessTokenRequestBody, null, 2)}`);
const clientIdAndSecretBase64 = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
axios.post(url, accessTokenRequestBody, {
headers: {
'Content-Type': 'application/application/x-www-form-urlencoded; charset=UTF-8',
'Authorization': `Basic ${clientIdAndSecretBase64}`
}
}).then((response) => {
let responseData = response.data;
console.log(`Pinterest ResponseData = ${JSON.stringify(responseData, null, 2)}`);
}).catch((e) => {
console.log(`${JSON.stringify(e.response.data)}`);
});
Here is the response I keep getting back:
{code:1, message:"Invalid request body"}
Here is the link to the documentation I am working with
https://developers.pinterest.com/docs/api/v5/#tag/Authentication
Please, what could I be doing wrong here, because I believed I provided everything they needed in the request.
Thanks in anticipation for your input.
const redirectUrl = process.env.PINTEREST_OAUTH_CALLBACK_URL;
const clientId = process.env.PINTEREST_APP_ID;
const clientSecret = process.env.PINTEREST_APP_SECRET;
let url = 'https://api.pinterest.com/v5/oauth/token';
let body = {
'code': code, //code is defined at the top as received from pinterest
'grant_type': 'authorization_code',
'redirect_uri': redirectUrl
};
// Fix code
let accessTokenRequestBody = Object.keys(body)
.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(body[k])}`)
.join('&');
console.log(`RequestBody =${JSON.stringify(accessTokenRequestBody, null, 2)}`);
const clientIdAndSecretBase64 = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
axios.post(url, accessTokenRequestBody, {
headers: {
'Content-Type': 'application/application/x-www-form-urlencoded; charset=UTF-8',
'Authorization': `Basic ${clientIdAndSecretBase64}`
}
}).then((response) => {
let responseData = response.data;
console.log(`Pinterest ResponseData = ${JSON.stringify(responseData, null, 2)}`);
}).catch((e) => {
console.log(`${JSON.stringify(e.response.data)}`);
});
I have a function which uses Axios to send a POST request which goes through successfully and I get the right response. Now I want to try using fetch to do the exact same POST request. Unfortunately, the fetch request returns a 415 Unsupported Media Type response error and I have no idea why.
Currently:
onBeforeUnload = () => {
try {
const defaultPresence = {
presence: 'AVAILABLE',
message: '',
};
const url = getServerURL() + urls.PRESENCE;
axios.post(
url,
defaultPresence,
{
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
},
);
} catch (error) {
console.log(error);
}
}
The fetch code I've used to replace the Axios POST request.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
body: defaultPresence,
});
fetch does not recognise plain objects as the body.
If you want to send JSON then you need to encode the data and set the content-type header yourself.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
"Content-Type": "application/json",
},
body: JSON.stringify(defaultPresence),
});
I use the following code using request which works as expected, got http response 200
var request = require('request');
var auth
var options = {
'method': 'POST',
'url': 'https://oauth2.k.de.com/oauth2/token',
'headers': {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'grant_type': 'client_credentials',
'scope': 'app:read'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
let body = JSON.parse(response.body);
….
Now I need to convert it to axios as request been deprecated but it’s not working for me ( I got http 400 response )
const axios = require('axios').default;
axios({
method: 'post',
'url': 'https://oauth2.k.de.com/oauth2/token',
data: {
'grant_type': 'client_credentials',
'scope': 'app:read'
},
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function (response: any) {
console.log("Head With Authentication :" + response);
}).catch(function (error: any) {
console.log("Post Error : " + error);
});
Any idea why with request library with the exact same data it works (http response 200) and in axios I got 400 ?
In request I put the grant_type etc in form and in axios in data, this is the only diffrencace I see, any idea?
This is the error I got
Request failed with status code 400
Should I use other rest libary if it cannot be done via axios ?
This is a bug, you might want to check this: https://github.com/axios/axios/issues/362
The problem is, because of axios interceptors, your Content-Type header is disappearing. If you have access and can change the backend, you can make it work with another header and set it on your client code. Otherwise if your code is working in a browser, you can try using URLSearchParams as suggested here.
I am trying to create a POST request in my reactjs app based on the following API request example:
Example API request
curl -X "POST" -H "Authorization: Basic ZjM4ZjAw...WY0MzE=" -d grant_type=client_credentials https://accounts.spotify.com/api/token
I'm supposed to be base64 encoding the text following "Basic" within the header.
How do I create this request in javascript using axios? This is what I have so far:
async componentDidMount() {
const encodedString = new Buffer('1ff56abe7792f426ea41a771d707d6690:1b2cca2dedd3949b0a6c5e1582446c9c5').toString('base64');
const [initSpotResponse] = await Promise.all([
axios.post('https://accounts.spotify.com/api/token', { headers: { 'Authorization': `Basic ${encodedString}` } })
]);
}
How do I include the "grant_type=client_credentials" part?
According to axios’ README, this is the Request method aliases for POST requests
axios.post(url[, data[, config]])
axios.post('https://accounts.spotify.com/api/token',
{ data: { grant_type: ‘client_credentials’} },
{ headers: { 'Authorization': `Basic ${encodedString}` } }
)
You could also do
const options = {
url: ‘https://accounts.spotify.com/api/token',
method: 'POST',
headers: { 'Authorization': `Basic ${encodedString}` },
data: { grant_type: ‘client_credentials’}
};
axios(options);
I'm trying to make an API request using fetch(browser). A token is required in the headers to make the request.
I can make successful requests in node (server side).
However, when making requests on the browser, the OPTIONS request fails with 401.
const order_url = new URL(process.env.API_URL + 'orders/');
const params = { type: 'amazon', status: 'in_queue' };
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
const headers = {
Authorization: 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
};
fetch(order_url, {
headers
})
.then(response => response.json())
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error)
})
The error i receive is "NetworkError when attempting to fetch resource."
What would be the correct configuration for this to work on the browser?
You are not sending headers properly.
Try this.
myHeaders = new Headers({
'Authorization': 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
});
and then
fetch(order_url, {
headers: myHeaders,
method: 'GET'
})