简体   繁体   中英

How can i store token value into my local javascript file

Hi am a beginner to Nodejs i have used passportjs token based authentication if the user logins it provides a token for each user i want to perform some operations based for the users who has token values for example if the user want to see the list of registered users they can view it if he has the token value. Now it provides me the token value perfectly in Postman but i don't know how to store it in a variable and call it via FRONT-END. I want do it via Front End(If he clicks the get users button) it should display the list of users.I have done that in POSTMAN it works finely i don't have an idea how to do it via frontend. My user Code(Login/Logout)

var express = require('express');
var router = express.Router();
var User = require('../models/user');
var passport = require('passport');
var Verify    = require('./verify');
/* GET users listing. */
router.route('/')
.get(Verify.verifyOrdinaryUser, function(req, res, next) {
    User.find({}, function (err, users) {
            if (err) throw err;
            res.json(users);
        });
});
router.post('/register', function(req, res, next) {
    User.register(new User({ username : req.body.username }),req.body.password, function(err, user) {
        if (err) {
            return res.status(500).json({err: err});
        }
        user.save(function(err,user) {
            passport.authenticate('local')(req, res, function () {
                return res.status(200).json({status: 'Registration Successful!'});
            });
        });
    });
});
router.post('/login', function(req, res, next) {
    passport.authenticate('local', function(err, user, info) {
        if (err) {
            return next(err);
        }
        if (!user) {
            return res.status(401).json({
                err: info
            });
        }
        req.logIn(user, function(err) {
            if (err) {
                return res.status(500).json({
                    err: 'Could not log in user'
                });
            }
            var token = Verify.getToken(user);
            res.status(200).json({
                status: 'Login successful!',
                success: true,
                token: token
            });
        });
    })(req,res,next);
});
router.get('/logout', function(req, res) {
        req.logout();
    res.status(200).json({
        status: 'Bye!'
    });
});
module.exports = router;

Main.js File. In this main.js file i want to send that token in this get method any idea?

$(".get-users-button").click(function() {
  $.ajax({
      method: "GET",
      url: " http://localhost:3000/users"
    })
    .done(function(msg) {
      console.log(msg);
      template(msg);
    });
});

As per the documentation for Passport:

If authentication succeeds, the next handler will be invoked and the req.user property will be set to the authenticated user.

Now if I'm understanding your question correctly, you want to pass the token value you obtain from:

var token = Verify.getToken(user)

to the view in which your front-end can do something with. You can pass variables to the view using the following middleware:

app.use((req, res, next) => {
  res.locals.token = Verify.getToken(req.user)
  next()
}

See the documentation for res.locals for more details.


Example usage:

app.js

const express = require('express')
const app = express()

app.set('view engine', 'pug')

app.use((req, res, next) => {
  res.locals.text = 'asdf'
  res.locals.token = 'abc'
  next()
})

app.get('/', (req, res) => {
  res.render('index')
})

app.listen(3000, () => {
  console.log('listening on 3000')
})

views/index.pug

doctype html
html
  head
    title= title
  body
    h1= text
  script.
    console.log('#{token}')

When you get back a successful response from the POST to your /login endpoint, store the token on client-side (eg, window.localStorage.setItem('<your-namespace>-user-token', <the token goes here>); )

Then, when user clicks the 'get-users-button', get the token out of storage (eg, window.localStorage.getItem('<your-namespace>-user-token'); and store it in a variable if you want.

Then, on your request to get users, add your { 'x-access-token': <token variable goes here> } to your request headers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM