【问题标题】:Save and get express.js token from local storage从本地存储中保存并获取 express.js 令牌
【发布时间】:2015-11-21 18:51:20
【问题描述】:

我正在使用带有 Express.js 的 Node 并尝试使用 JWT 进行身份验证,在用户登录后生成令牌并将其保存到本地存储,但是我不知道如何获取令牌进行身份验证。 这是我正在使用的代码:

登录视图:

$.ajax({
            type: 'POST',
            url: base_url + "login",
            data: postData,
            dataType: 'json',
            success: function(data){
                // console.log(data1);
                // alert(data);
                _(data);
                if(data.success === false){
                    showError(data.msg);
                }else{
                    showError(data.msg);
                    window.localStorage.setItem("authToken", data.token);

                    var token = window.localStorage.getItem('authToken');
                    if (token) {
                      $.ajaxSetup({
                        headers: {
                          'x-access-token': token
                        }
                      });
                    }
                }
            }
        });

这是我在访问任何路由之前用来检查的路由身份验证:

router.use(function(req, res, next){
    var token = req.headers['x-access-token'];
    console.log(token);
    if (token) {
        // verifies secret and checks exp
        jwt.verify(token, app.get('superSecret'), function(err, decoded) {      
            if (err) {
                return res.json({ success: false, message: 'Failed to authenticate token.' });    
            }else{
                // if everything is good, save to request for use in other routes
                req.decoded = decoded;    
                next();
            }
        });

      } else {

        // if there is no token
        // return an error
        return res.status(403).send({ 
            success: false, 
            message: 'No token provided.' 
        });
      }
});

在 console.log(token) 我得到一个 Undefined variable ,似乎我不知道如何从路由访问令牌。

非常感谢。

【问题讨论】:

  • 您是否验证过(通过浏览器的开发者工具)实际发送了标头?
  • @mscdex 当我上网时,我看不到 x-access-token 作为请求标头或响应标头
  • 您没有在对$.ajax 的调用中正确设置标题。查看这篇文章以了解如何设置标题 stackoverflow.com/questions/39947698/… - 您需要在传递给 ajax 函数的对象中使用 headers 字段,而不是在成功函数中。

标签: node.js express local-storage token jwt


【解决方案1】:

“x-access-token”必须注册为允许的标头

response.setHeader("Access-Control-Allow-Headers", "x-access-token, mytoken");

查看这篇文章: How do CORS and Access-Control-Allow-Headers work?

【讨论】:

    猜你喜欢
    • 2017-09-22
    • 1970-01-01
    • 2018-11-12
    • 2020-10-25
    • 2019-09-23
    • 2018-11-14
    • 2021-04-12
    • 2016-01-19
    • 2019-10-26
    相关资源
    最近更新 更多