I've been trying to use Axios in order to check whether or not a user is authenticated server side (Node+Express+Passport).
If a user is authenticated, the server sends back a "Connected" string, else, it sends back a "Not connected" string.
Router.get('/isAuth', function (req, res, next) {
if (req.isAuthenticated()) {
return res.status(200).send('Connected');
} else {
return res.status(200).send('Not connected');
}
});
I wrote a simple function to check the server's response:
function isAuth() {
return axios.get('http://localhost:3000/endpoints/isAuth')
.then((response) => {
if (response.data === "Connected") {
return true;
} else {
return false;
}
})
.catch((error) => {
console.log(error)
})
}
The function is supposed to return true if the user is connected, and vice-versa.
Now, when I try to log the the function's results in the console, this is what I get:
Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
__proto__ : Promise
[[PromiseStatus]] : "resolved"
[[PromiseValue]] : false
As you can see, the value returned is a promise object, whereas the desired output would preferably be a "True" or "False".
isAuth does an async request which will take some time. therefore it cannot return true or false directly. it will instead return a promise that gets that boolean value. to access your boolean value, you have to treat your isAuth() function as a promise:
isAuth().then(isAuthenticated => console.log(isAuthenticated));
Update:
this code:
var test = isAuth();
will return the promise syncronously and won't wait for the reponse result
if you want to access the reponse of the promise, you need to use then:
test.then(value => ...);
if you really want to do a syncronous http request (blocks your app, untill the request is resolved) you can checkout https://github.com/ForbesLindesay/sync-request
but you actually don't want to use if it is not for test purpose only.
another thing you could consider is the use of async/await which comes with node 7.6 but you first should fully understand the concept of promises
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With