【问题标题】:consume rest auth api in nodejs在nodejs中使用rest auth api
【发布时间】:2020-01-09 08:32:45
【问题描述】:

我有一个在 www.website.com/users/login 运行的 api。我想在我的 nodejs 前端使用 api。我想将从 /login 收到的令牌传递给所有其他路由。在这里,我试图将登录后收到的令牌传递到注销路由。

Api注销代码-

router.post('/users/logout',auth, async(req,res)=>{
    try{
        req.user.tokens=req.user.tokens.filter((token)=>{
            return token.token !==req.token
        })

        await req.user.save()

        res.send()
    }catch(e){
        res.status(500).send()
    }
})

客户端代码

app.post('/users/login', function (req, res) {

var email = req.body.email;
var password = req.body.password;
var form = {
    email,
    password
}

request.post({
    url: "https://website.com/users/login",
    body: form,
    json: true
}, function (error, response, body) {
    console.log('error:', error)
    console.log('body:', body.errmsg);
    console.log(body);
    if (body.user) {
        let auth = body.token
        console.log(auth) //I want to pass this auth to /logout
    } else {
        res.render('login', {
             email,
            password
        })
    }   
})

注销路由。我想将令牌传递给注销路由,以便用户可以注销?

app.post('/users/logout', function (req, res, next) {
request.post({
        url: "https://website.com/users/logout",
        headers: {
            'Authorization': auth
        },
    }, function (error, response, body) {
        console.log('error:', error)
        console.log('response:', response);
        console.log('body:',body);
    })
})

请帮助我了解如何使用从登录收到的令牌到其他路由。我让邮递员从 auth 继承,但我很难使用这个 api。

【问题讨论】:

    标签: javascript node.js mongodb rest api


    【解决方案1】:

    首先,为什么您需要一个令牌才能退出?您没有在 auth 中间件上分享您的完整代码。您要做的是将令牌存储在本地存储中。例如这是一个简单的客户端登录

    const login = (username, password) =>{
      //http call
    axios.post('https://www.websites.com', {username, password})
    .then(response=>{
    //when the request is successful set the token to local storage
    const {token} = response.data;
    //this will set your token in local storage
    localstorage.setItem('token', token)'
    so you can decide to append your token to the routes
    
    })
    }
    

    如果想从 nodejs 前端注销,您可以为令牌设置到期日期,如果您想要更严格的注销,请查看 it has already been answered here

    【讨论】:

      猜你喜欢
      • 2014-09-21
      • 2020-08-29
      • 2015-08-09
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 2018-08-19
      • 1970-01-01
      相关资源
      最近更新 更多