【问题标题】:api authentcation in nodejs节点js中的api认证
【发布时间】:2017-11-26 20:46:29
【问题描述】:

我正在使用passport,jwt在nodeJs中进行身份验证。我已经创建了api。它在邮递员中运行良好。但我坚持渲染前端并显示错误消息。我的api是:

app.post('/api/login',(req, res, next) => {
        if (req.body.name == '' || req.body.password == '') {
            res.json({
                message: 'Please fill all the fields'
            })
            req.flash('errorMsg', 'Please fill all the fields')
        } else if (!regExp.test(req.body.name)) {
            res.json({
                message: 'Only alphabets and numbers are allowed'
            })
        } else if ((req.body.password.length < 4)) {
            res.json({
                message: 'Password must be 4 character length and more'
            })
        }
        else {

            let user = users[_.findIndex(users, {
                name: req.body.name
            })];
            if (user === undefined) {
                res.status(401).json({
                    message: 'User not defined'
                })

            } else {
                if (user.password === req.body.password) {
                    let payload = {
                        id: user.id
                    };
                    let token = jwt.sign(payload, config.jwtSecret);
                    localStorage.setItem('token', token);
                    res.json({
                        message: "ok",
                        token: token
                    });

                } else {
                    res.status(401).json({
                        message: 'Password did not match'
                    })

                }
            }
        }
    });

如何在前端显示这些错误。我使用把手作为查看引擎。例如,如果密码不匹配,则在前端显示密码错误消息。我已经设置了使用护照 jwt 策略的中间件。

【问题讨论】:

  • 您正在创建一个 API。 API 只是后端。其他人必须向您的 API 发送请求并使用响应。如果您有其他使用 res.render 而不是 res.json 的路由,那么您应该使用 javascript 的 XHR (AJAX) 请求来获取您想要的消息(并提交表单)

标签: node.js express passport.js


【解决方案1】:

“如何在前端显示这些错误”

您必须在客户端捕获/处理从服务器端抛出的错误,正如其未定义所指出的,您应该使用 AJAX 请求并处理作为响应发送的错误(由状态代码标识)你的服务器端。

然后您可以显示一个警告框,说明发生的错误。下面是在使用查询 ajax http://api.jquery.com/jquery.ajax/ 的情况下可能会出现的示例

$.ajax("www.yourapplication.com/api/login", {
    dataType:"JSON"
    data: { password=password, name='example' }
}).succes(function (result) {
    // redirect to authenticated page
}).error(function (jqXHR, textStatus, errorThrown) {
    alert('Error message');
});

【讨论】:

  • 这是您第一个答案的良好开端。但是,最好在这个答案中包含一个工作代码示例,以便答案是高质量的并且可以被 OP 接受
猜你喜欢
  • 2021-01-09
  • 2015-04-17
  • 2018-05-09
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2017-02-14
相关资源
最近更新 更多