如何在不获取的情况下获取路线的json

时间:2019-01-31 11:07:41

标签: node.js express jwt

我有一条路线,该路线会向我返回带有用户授权的json。

router.get('/test', function(req, res,next ) {

    var token = req.cookies.auth;
    if (!token) return res.status(401).send({ message: ""});

    jwt.verify(token, config.secret, function(err, decoded) {
      if (err) return res.status(500).send({ message: "Failed to authenticate token."});
      User.findById(decoded.id,function(err,user){
          if (err) return res.status(500).send({ message: "problmes found user, sorry "});

          if(!user) return res.status(404).send({message: "user not found "});
          res.status(200).send({message:user.role});
      });

    });
  });

我想将json响应捕获到变量中,以便通过另一条路径来授权操作。

router.get('/', function(req, res, next) {

  if (jsonresponse == grant ){
  var allMusique;
  var idMaxMusique;
  MongoClient.connect(url, function(err, db) {
      if (err) throw err;
      var dbo = db.db("projet_node");
      dbo.collection("musiques").find({}).toArray(function(err, result) {
          if (err) throw err;
          allMusique = result;
          var size = allMusique.length-1;
          idMaxMusique = parseInt(result[size].id)+1;
          res.render('musiques', { resultat: allMusique, idMax: idMaxMusique });
      });
      });}
      else{
          res.render('unauthorized');
      }
});

1 个答案:

答案 0 :(得分:1)

创建 Controllers / middlewares / authenticate.js 文件并编写以下代码

const jwt = require('jsonwebtoken')
module.exports = (req, res, next) => {
  const token = req.headers['token'] || req.body.token || req.cookies.token;
  if (token) {
    try {
      req.decoded = jwt.verify(token, JWT_SECRET_KEY) 
      // JWT_SECRET_KEY -> config.secret
      next()
    } catch (err) {
      res.status(403)
         .send({ success: false, message: 'Failed to authenticate token.' })
    }
  } 
  return res.status(403).send({
    success: false,
    message: 'No token provided.'
  })
}

创建 Controlller / UserController.js 文件

exports.getUser = function (req, res) {
  // Perform Your requirement of code 
  // return Something
}
exports.getUserTest = function (req, res) {
  // Perform Your requirement of code 
  // return Something
}

在您的 routes / routes.js 文件中

const authenticate = require('./Controllers/middlewares/authenticate');
const UserController = require('./Controllers/UserController');

// Routes with authentication. User must be login for get this routes
 router.get('/getUser', authenticate, UserController.getUser);  
// Routes without authentication. No need to login
 router.post('/getUserTest', UserController.getUserTest);

最重要的 require('PathOfFile')正确,或者总是总是在require中仔细检查文件和文件夹的路径。