Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何检查用户是否拥有有效的JWT,然后对其进行授权?_Node.js_Reactjs_Express_Jwt_Mern - Fatal编程技术网

Node.js 如何检查用户是否拥有有效的JWT,然后对其进行授权?

Node.js 如何检查用户是否拥有有效的JWT,然后对其进行授权?,node.js,reactjs,express,jwt,mern,Node.js,Reactjs,Express,Jwt,Mern,我的第一个项目是制作一个MERN Stack CRUD应用程序,我被卡住了。我已经成功地创建了一个成功的API。现在,我想把它应用到前端,如果你想看的话,这是我的API: const express = require('express'); const router = express.Router(); const bcrypt = require('bcryptjs'); const config = require('config'); const jwt = require('json

我的第一个项目是制作一个MERN Stack CRUD应用程序,我被卡住了。我已经成功地创建了一个成功的API。现在,我想把它应用到前端,如果你想看的话,这是我的API:

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const config = require('config');
const jwt = require('jsonwebtoken');
const auth = require('../../middleware/auth');

const User = require('../../models/User.model');

router.post('/', (req, res) => {
  const { email, password } = req.body;

  if (!email || !password) {
    res.status(400).json({ msg: 'Please fill out all the mandatory fields' });
  }

  User.findOne({ email }).then((user) => {
    if (!user) res.status(400).json({ msg: "User doesn't exists!" });

    // Validate Password.
    bcrypt.compare(password, user.password).then((isMatch) => {
      if (!isMatch) return res.status(400).json({ msg: 'Invalid Credentials' });

      jwt.sign(
        { id: user.id },
        config.get('jwtSecret'),
        {
          expiresIn: 3600,
        },
        (err, token) => {
          if (err) throw err;
          res.json({
            token: token,
            user: {
              id: user.id,
              name: user.name,
              email: user.email,
            },
          });
        }
      );
    });
  });
});

router.get('/user', auth, (req, res) => {
  User.findById(req.user.id)
    .select('-password')
    .then((user) => res.json(user));
});

module.exports = router;
现在,我知道我需要创建一个表单,但是,在React中使用Axios获取数据时,如何避免发送401请求。错误如下 js:177获取http://localhost:9000/api/employees 401(未经授权)

这意味着API是成功的,但是在前端我需要做什么呢

我是否应该在Axios get请求中创建一个catch块,以便在用户未经身份验证的情况下重定向到登录路由,但是,如何检查JWT?我已经为此在我的后端创建了一些东西;代码如下:

const config = require('config');
const jwt = require('jsonwebtoken');

function auth(req, res, next) {
  const token = req.header('x-auth-token');

  if (!token) res.status(401).json({ msg: 'No Token, No Authorization!' });

  try {
    const decoded = jwt.verify(token, config.get('jwtSecret'));

    req.user = decoded;
    next();
  } catch (e) {
    res.status(400).json({ msg: 'Token is not Valid!' });
  }
}

module.exports = auth;

我正在使用React钩子,但解决方案的任何想法都会奏效。

好的,因此,StackOverflow社区很糟糕。我不得不自己写答案。
您必须使用POST请求提供数据,然后使用中间件进行检查。

将路由器功能、内置逻辑、身份验证全部放在1中是非常糟糕的做法。你应该分头行动code@Ifaruki我确实拆分了我的代码,它只是代码的一部分。