admin管理员组

文章数量:1291319

I am learning JWT with NodeJs. I am stuck at passing the JWT in header actually i do not know how to do this.

index.js file

var express = require('express'),
 app = express(),
 routes = require('./routes'),
 bodyParser = require('body-parser'),
 path = require('path'),
 ejs = require('ejs'),
 jwt = require('jsonwebtoken');

app.use(bodyParser.urlencoded({ extended: false })); 
app.use(bodyParser.json());

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.post('/home',routes.loginUser);

app.get('/', function(req, res) {
  res.render('index');
});

app.get('/home',function(req, res) {
  jwt.verify(req.token, 'qwertyu6456asdfghj', function(err, data) {
    if (err) {
      res.sendStatus(403);
    } 
  });
});

 app.listen(3000,function(){
  console.log("Server running at Port 3000");
});

routes/index.js file

var  jwt = require('jsonwebtoken');

exports.home = function(req, res){
  res.render('home',{error: false});
};

exports.loginUser = function(req, res) {
    var uname = req.body.Username;
    var pwd = req.body.Password;

    if(uname && pwd === 'admin'){
        res.render('home');

    var token = jwt.sign({ user: uname }, 'qwertyuiopasdfghj');
    console.log('Authentication is done successfully.....');
    console.log(token);
    }

    response.json({
        authsuccess: true,
        description: 'Sending the Access Token',
        token: token
    });
};

when i run the application i am getting the token in console.log but How can I pass token in header and store it in localStorage of browser?

I am learning JWT with NodeJs. I am stuck at passing the JWT in header actually i do not know how to do this.

index.js file

var express = require('express'),
 app = express(),
 routes = require('./routes'),
 bodyParser = require('body-parser'),
 path = require('path'),
 ejs = require('ejs'),
 jwt = require('jsonwebtoken');

app.use(bodyParser.urlencoded({ extended: false })); 
app.use(bodyParser.json());

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.post('/home',routes.loginUser);

app.get('/', function(req, res) {
  res.render('index');
});

app.get('/home',function(req, res) {
  jwt.verify(req.token, 'qwertyu6456asdfghj', function(err, data) {
    if (err) {
      res.sendStatus(403);
    } 
  });
});

 app.listen(3000,function(){
  console.log("Server running at Port 3000");
});

routes/index.js file

var  jwt = require('jsonwebtoken');

exports.home = function(req, res){
  res.render('home',{error: false});
};

exports.loginUser = function(req, res) {
    var uname = req.body.Username;
    var pwd = req.body.Password;

    if(uname && pwd === 'admin'){
        res.render('home');

    var token = jwt.sign({ user: uname }, 'qwertyuiopasdfghj');
    console.log('Authentication is done successfully.....');
    console.log(token);
    }

    response.json({
        authsuccess: true,
        description: 'Sending the Access Token',
        token: token
    });
};

when i run the application i am getting the token in console.log but How can I pass token in header and store it in localStorage of browser?

Share Improve this question asked Jan 17, 2018 at 10:41 Nikhil SavaliyaNikhil Savaliya 2,1664 gold badges26 silver badges45 bronze badges 5
  • This happens on the client side. Are you calling your express app from web? android? ios? each client needs to handle the tokens and attach it to requests as this header: "Authorization": "Bearer <token>" ('Bearer'is just a convention for using this with passport) – ChicoDelaBarrio Commented Jan 17, 2018 at 10:51
  • @ChicoDelaBarrio I know how can i do this ? – Nikhil Savaliya Commented Jan 17, 2018 at 10:52
  • it depends on the client. I would remend starting from using postman link to test your requests – ChicoDelaBarrio Commented Jan 17, 2018 at 10:55
  • while i am sending response using res.json({ authsuccess: true, description: 'Sending the Access Token', token: token }); I am getting this error -> Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client – Nikhil Savaliya Commented Jan 17, 2018 at 10:58
  • 1 it's because you can't use 'respinse.json()' after 'resposnse.render'. You can only respond once. This error is not JWT related – ChicoDelaBarrio Commented Jan 17, 2018 at 11:00
Add a ment  | 

2 Answers 2

Reset to default 6

So you want to send the token to frontend but not in the body.

The Remended way to do so is to use cookies. You can set the token in the cookie and it can be automatically accessed in front-end and in the backend.

res.cookie('tokenKey', 'ajsbjabcjcTOKENajbdcjabdcjdc');

Using authorization headers is also a good approach, but again, in front-end, you have to fetch the token from headers and then save in localStorage or cookie, which you don't have to do in case of cookie.

res.header(field [, value]);

As @ChicoDelaBarrio told you, it depends on the client. Postman is a good place to start checking your backend. But after you have your server working, you have to start working in your client side.

If you want a plete backend example about JWT in Node.js, with Refresh token included, I reend you this post about it: Refresh token with JWT authentication in Node.js Probably you can reuse most of the code. In this case the header is not created with BEARER, but with JWT at the beginning, but it works the same

本文标签: javascriptPass JWT in HeaderStack Overflow