如何在Node.js的POST / GET请求标头中添加x-auth-token?

时间:2019-06-11 20:34:21

标签: node.js express

我有一个/ register路径,该路径向用户返回一个令牌(由auth中间件生成)。该经过身份验证的用户将可以查看和发布。但是,我不知道如何将该令牌存储在浏览器(或数据库)中以及如何通过x-auth-token将其包含在标头中。在邮递员中,我可以将其添加到标头中,但是我不知道如何以HTML形式进行添加。

auth.js(身份验证中间件)

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

// middleware function, next so it moves on to the next middlware
module.exports = function(req, res, next) {
  //get the token from header
  const token = req.header('x-auth-token');

  //Check if not token
  if (!token) {
    return res.status(401).json({ msg: 'No token, authorization denied' });
  }

  //Verify token if exist
  try {
    const decoded = jwt.verify(token, config.get('jwtSecret'));
    req.user = decoded.user;
    next();
  } catch (err) {
    res.status(401).json({ msg: 'Token is not valid' });
  }
};

posts.js

// @ route    POST api/posts
// @desc      Create a post
// @access    Private
router.post(
  '/',
  [
    auth,
    [
      check('title', 'Title is required')
        .not()
        .isEmpty()
    ]
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    try {
      const user = await User.findById(req.user.id).select('-password');

      //user information (name and avatar) comes from the databse, not the request
      const newPost = new Post({
        title: req.body.title,
        body: req.body.body,
        name: user.name,
        avatar: user.id,
        user: req.user.id
      });
      const post = await newPost.save();
      res.json(post);
    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server Error');
    }
  }
);

post.handlebars(帖子形式)

 <form class="form" action="/api/posts" method="post" >
                <div class="form-group">
                    <input type="text" placeholder="What is your idea?" name="title" requried>
                </div>

                <div class="form-group">
                    <input type="text" placeholder="Let us know more detail. What is the story. How did you come up with it? 
Why do you think people would need it etc" name="body">
                </div>
                <input type="submit" value="Post" class="button green-button" />

            </form>

users.js(注册)

.
.
.

      jwt.sign(
        payload,
        config.get('jwtSecret'),
        { expiresIn: 60 * 60 * 100 },
        (err, token) => {
          if (err) throw err;
          res.json({ token });
          // req.flash('You seccessfully registered your account');
          // res.redirect('/user/login');
        }
      );
    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server error');
    }
  }
);

1 个答案:

答案 0 :(得分:2)

通常,您希望将令牌作为cookie存储在浏览器中。 Cookie始终与请求一起发送到后端,因此您不需要特殊的逻辑即可包含标头。