【问题标题】:SMS are not saving in database短信未保存在数据库中
【发布时间】:2021-12-31 19:04:11
【问题描述】:

Nodejs、MongoDB、Rest API 我在这里使用 twilio 服务在 MongoDB 数据库中发送手机 otp SMS,SMS 正在发送并且没有错误,但 otps 没有保存在数据库中。请帮我 如何将 otps 保存在数据库中。

try {
        const { phone } = req.body;
        const user = await User.findOne({ phone: phone });

        if (!user) {
            return res.status(404).json({ success: false, message: 'Phone not found.' 
            })
        }

        const accountSid = process.env.TWILIO_ACCOUNT_SID;
        const authToken = process.env.TWILIO_AUTH_TOKEN;
        const client = require('twilio')(accountSid, authToken);

        client.verify.services.create({friendlyName: `My First Verify Service` })
            .then(service => console.log(service.sid));

        client.verify.services(process.env.TWILIO_SERVICES_KEY)
            .verifications
            .create({ to: user.phone, channel: `sms ` })
            .then(verification => {
            console.log(verification.status)
        });

        client.verify.services(process.env.TWILIO_SERVICES_KEY)
           .verificationChecks
           .create({to: user.phone, code: `${user.phoneOtp}`})
           .then(verification_check => console.log(verification_check.status));



        await user.save();


        return res.status(200).json({ success: true, message: 'OTP sended to your 
             registered phone number.' });
        } catch (err) {
            return res.status(200).json({ success: false, message: 'OTP not send try 
             again' });
        }

【问题讨论】:

  • 所以你正在等待 user.save() 但是 user.phoneOtp 何时何地被设置?我没有看到这种情况发生
  • 您似乎正在发送并尝试在同一请求中检查 OTP,这将不起作用,因为在您发送之前,您的用户将没有要检查的 OTP 代码。使用 Twilio 验证时也不需要存储 OTP 代码。我会检查 Twilio 验证的文档并重试。

标签: node.js mongodb rest twilio


【解决方案1】:

尝试将await user.save(); 放入发送短信的服务中。你可以把它放在.then里面。

【讨论】:

    【解决方案2】:

    从我在这里看到的情况来看,您还没有将 OTP 保存到数据库中。 发送 OTP 后立即添加 user.phoneOtp = code;await user.save(); 在继续之前。

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      相关资源
      最近更新 更多