You haven't really explained what the issue is but I'm going to assume that it's because the access token and instance URL aren't being returned correctly from the
auth()
method. This is because the authentication is using an XML HTTP request which relies on the Javascript promises API.
What's happening is you're calling the
auth()
method which starts the
axios.post()
which you can see is returning a promise, you're then subscribing to that promise to get the access token and instance URL, but you're returning from the
auth()
method before that promise has had chance to complete. When the method returns, it doesn't know what the
res
variable is.
You need to adjust your code to
return the promise from the auth() method and then subscribe to the result. Something similar to:
const auth = ()=>
return axios.post(`${endpoint}/services/oauth2/token`,{
body:`grant_type = password&client_id=${clientId}&
client_secret=${clientSecret}&
username=${username}&
password=${password}`,
headers: {
"Authorization": 'Basic' + Buffer.from(`${client_Id}:${clientSecret}`).toString('base64'),
"Content-Type": "application/x-www-form-urlencoded",
}
})
.then(res => res.json())
.then(json => {
console.log('fetching token')
console.log(res)
return json;
})
.catch(error => console.log(error));
}
const salesforce=( res)=>{
auth(config).then(response => {
const instanceToken = response.access_token;
const instance_url= response.instance_url;
return fetch(`{}`)
});
}
Another way would be to make your methods use
async
and
await
which lets your bypass some of the headaches. For example:
const auth = async () => {
try {
const response = await axios.post(..);
return response ? response.json() : undefined;
} catch (err) {
console.error(err);
return undefined;
}
}
const salesforce = async (res) => {
const response = await auth();
if (response) {
const access_token = response.access_token;
const instance_url = response.instance_url;
}
};