Trying to get the access_token data from `token--url` and use it for GET request to fetch the RESTapi data of another application(which is not developed by me. The token which we get using POST method will be used to get access for fetching the RESTapi data using GET method) and also need to use refresh token after the expiry of access_token automatically.
The token data will look like below:
{
"scope": "abcdefg",
"access_token": "adq3e3e2d23e23",
"refresh_token": "dwned323en232je",
"expires_in": 1799,
"token_type": "Bearer"
}
What I have tried:
function Post() {
var urHeaders = new Headers();
urHeaders.append("API-version", "2");
urHeaders.append("Accept", "application/json");
urHeaders.append("Content-Type", "application/x-www-form-urlencoded");
urHeaders.append("Authorization", "Basic <wwww>");
var raw = "grant_type=password&username=name@yyy.com&password=xyz";
var requestOptions = {
method: 'POST',
headers: urHeaders,
body: raw,
redirect: 'follow'
};
const first = fetch("https://<--url-->/oauth2/token", requestOptions)
const second = first.then(response => response.json())
return second;
}
var token = Post().then((data) => {
console.log('This is your data', data)})
function Test() {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", `Bearer ${token.then((data)=>{data.access_token})}`);
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
const promise = fetch("https://<--url--towhich--access_token--is--passed>", requestOptions)
const data = promise.then(response => response.json())
return data;
}
export let use = Test();
export default (req, res) => {
res.statusCode = 200
use.then(data => {
res.json(JSON.stringify(data))
})
.catch(err => console.log(err))
}