-1

I have an api running at www.website.com/users/login .I want to consume the api in my nodejs frontend . I want pass the token received from /login to all other routes. Here i am trying to pass the token recieved after login to logout route.

Api logout code-

router.post('/users/logout',auth, async(req,res)=>{
    try{
        req.user.tokens=req.user.tokens.filter((token)=>{
            return token.token !==req.token
        })

        await req.user.save()

        res.send()
    }catch(e){
        res.status(500).send()
    }
})

CLient side code

app.post('/users/login', function (req, res) {

var email = req.body.email;
var password = req.body.password;
var form = {
    email,
    password
}

request.post({
    url: "https://website.com/users/login",
    body: form,
    json: true
}, function (error, response, body) {
    console.log('error:', error)
    console.log('body:', body.errmsg);
    console.log(body);
    if (body.user) {
        let auth = body.token
        console.log(auth) //I want to pass this auth to /logout
    } else {
        res.render('login', {
             email,
            password
        })
    }   
})

Logout route .I want to pass token to the logout route so that the user can logout?

app.post('/users/logout', function (req, res, next) {
request.post({
        url: "https://website.com/users/logout",
        headers: {
            'Authorization': auth
        },
    }, function (error, response, body) {
        console.log('error:', error)
        console.log('response:', response);
        console.log('body:',body);
    })
})

Please help me understand how to use the token recieved from login to other routes. I had postman inherit from auth but i am having hard time to consume this api.

1 Answers1

0

first, why do you need a token to log out? you didn't share your complete code on the auth middleware. what you will like to do is store your token in local storage. for example this is a simple client-side login

const login = (username, password) =>{
  //http call
axios.post('https://www.websites.com', {username, password})
.then(response=>{
//when the request is successful set the token to local storage
const {token} = response.data;
//this will set your token in local storage
localstorage.setItem('token', token)'
so you can decide to append your token to the routes

})
}

if want to logout from a nodejs frontend you can set an expiration date for your token and if you want a more strick logout you check this out it has already been answered here

Alcantara
  • 120
  • 7