节点js API REST服务身份验证翻译文本邮件节点邮件程序

时间:2019-04-22 11:55:44

标签: node.js angularjs express

我已经使用node js和express开发了REST API。 当用户进行注册时,我使用节点邮件程序发送邮件。 我有身份验证服务(POST方法),该服务读取应用程序传递的语言代码,并发送包含翻译后的文本和令牌的电子邮件以验证注册。带有令牌的链接是发送其他邮件的GET请求。 我如何对GET方法说使用哪种语言代码,以便可以发送带有翻译的邮件?

您好实现了以下代码来验证令牌:

// Verification token
router.get('/verification/:language/:token/', function(req, res, next) {
const language = req.params.language;

console.log(language); 


// Check for validation errors
var errors = req.validationErrors();
if (errors) return res.status(400).send(errors);

// Find a matching token
Token.findOne({ token: req.params.token }, function (err, token) {
//if (!token) return res.status(400).send({status: 'ko',error: {type: 'not-verified', msg: 'We were unable to find a valid token. Your token my have expired.'}} );
if (!token) return res.redirect('https://localhost/expiredtoken');



// If we found a token, find a matching user
User.findOne({ _id: token._userId }, function (err, user) {
  if (!user) return res.status(400).send({ msg: 'We were unable to find a user for this token.' });

  //if (user.isVerified) return res.status(400).send({status: 'ko',error:{type: 'already-verified', msg: 'This user has already been verified.'}});
  if (user.isVerified) return res.redirect('https://localhost/userverified');

  // Verify and save the user
  user.isVerified = true;
  user.save(function (err) {
    if (err) { return res.status(500).send({ msg: err.message }); }
    //res.status(200).send({status: 'ok', data: { msg: 'The account has been verified. Please log in.'}});
    res.redirect('https://localhost/login');


    //
    var text_email;
    if (language == 'en') {
      text_email = 'Hi'
    }
    if (language == 'it') {
      text_email = 'Ciao'
    }


    var client = nodemailer.createTransport(sgTransport(options));

    var email = {
        from: 'noreply@test.com',
        to: user.email,
        subject: 'Registration successfully confirmed',

        text: text_email
      };

    client.sendMail(email, function(err, json){
        if (err){
            return res.status(500).send({ msg: err.message });
        }
        else {
            res.status(200).send({status: 'ok', data: { msg: 'A verification email has been sent to ' + user.email + '.'}} )
        }
    });



    //

        });
    });
});

});

验证有效,并且发送邮件但应用程序因以下错误而崩溃: 错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头

请帮忙吗?

2 个答案:

答案 0 :(得分:1)

使用GET http://localhost/route?language=en

如果您使用的是express,则可以通过路由处理程序中的req.query.language来访问语言的值。

答案 1 :(得分:0)

您可以使用GET方法,并在路径中添加参数。

例如:

路线:http://your-app-domain/route?language=en

获取语言:

...
app.get('/route', (req, res) => {
  const language = req.query.language;
  console.log(language); // en
});

http://expressjs.com/pt-br/api.html#express.urlencoded

希望这会有所帮助!