Подтверждение аккаунта через почтовый узел js и Angular 5 - PullRequest
0 голосов
/ 26 июня 2018

Я строю SPA, где пользователь регистрируется и получает электронное письмо. При нажатии кнопки подтверждения я беру токен с пути и пытаюсь отправить его на NodeJs

activation.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { RestApiService } from '../../rest-api.service';
import { DataService } from '../../data.service';

@Component({
  selector: 'app-activation',
  templateUrl: './activation.component.html',
  styleUrls: ['./activation.component.css']
})
export class ActivationComponent implements OnInit {

  temporarytoken: string;
  public sub: any;

  constructor(public route: ActivatedRoute, private router: Router, private 
  rest: RestApiService, private data: DataService) { }  

  ngOnInit() {
    this.sub =this.route.params.subscribe(params => {
  this.temporarytoken= params['temporarytoken'];
  this.updateAccount();
});

if(this.temporarytoken == null){
  this.router.navigate(['/home']);
}
 }

 async updateAccount(){
   try{
    const data = await this.rest.post(
   'http://localhost:3030/api/accounts/activate', {
     temporarytoken: this.temporarytoken
   },
 );
} catch {
 this.data.error(['message']);
}
}

 }

Узел маршрута JS

router.put('/activate', (req, res, next) => {
   User.findOne({ temporarytoken: req.body.temporarytoken }, (err, user) => {
       if (err) throw err;
      var token = req.body.temporarytoken;

        jwt.verify(token, secret, (err, decoded) => {
        if (err) {
            res.json({ success: false, message: 'Activation Link has Expired' 
    });
        }
        else if (!user) {
            res.json({ success: false, message: 'Activation Link has Expired' 
    });
        }
        else {
            user.temporarytoken = false;
            user.active = true;
            user.save(function (err) {
                if (err) {
                    console.log(err);
                }
                else {
                    nodemailer.createTestAccount((err, account) => {
                        let transporter = nodemailer.createTransport({
                            service: "gmail",
                            debug: true,
                            auth: {
                                user: "*******@gmail.com",
                                pass: "*********"
                            }
                        });
                        let mailOptions = {
                            from: '"Company" <********@gmail.com>""',
                            to: user.email,
                            subject: 'Welcome!!!',
                            text: 'hello account activated',
                            html: 'hello account activated'
                        };
                        transporter.sendMail(mailOptions, (error, info) => {
                            if (error) {
                                return console.log(error);
                            }
                            console.log('Message sent: %s', info.messageId);
                            console.log('emial entered', user.email);
                            console.log('Preview URL: %s', 
                    nodemailer.getTestMessageUrl(info));
                        });
                    });
                }
            });
            res.json({ success: true, message: 'Account Activated!' })
            }
          });
       });
    });

Когда я пытаюсь передать токен от почтальона, он выдает мне эту ошибку

events.js: 183 бросить эр; // необработанное событие error ^ ReferenceError: секрет не определен в User.findOne (C: \ Users \ manoj \ Desktop \ blue \ server \ router \ account.js: 133: 27) в C: \ Users \ manoj \ Desktop \ blue \ server \ node_modules \ mongoose \ lib \ model.js: 3950: 16 Немедленно. (C: \ Users \ Манодж \ Desktop \ синий \ сервер \ node_modules \ мангуст \ Lib \ query.js: 1516: 14) в Immediate._onImmediate (C: \ Users \ manoj \ Desktop \ blue \ server \ node_modules \ mquery \ lib \ utils.js: 119: 16) при runCallback (timers.js: 789: 20) в tryOnImmediate (timers.js: 751: 5) at processImmediate [as _immediateCallback] (timers.js: 722: 5) Сбой приложения [nodemon] - ожидание изменений файла перед запуском ...

если секрет снят, я получаю эту ошибку

events.js: 183 бросить эр; // необработанное событие error ^ JsonWebTokenError: должен быть указан jwt в Object.module.exports [как проверить] (C: \ Users \ manoj \ Desktop \ blue \ server \ node_modules \ jsonwebtoken \ verify.js: 39: 17) в User.findOne (C: \ Users \ manoj \ Desktop \ blue \ server \ router \ account.js: 133: 13) в C: \ Users \ manoj \ Desktop \ blue \ server \ node_modules \ mongoose \ lib \ model.js: 3950: 16 Немедленно. (C: \ Users \ Манодж \ Desktop \ синий \ сервер \ node_modules \ мангуст \ Lib \ query.js: 1516: 14) в Immediate._onImmediate (C: \ Users \ manoj \ Desktop \ blue \ server \ node_modules \ mquery \ lib \ utils.js: 119: 16) при runCallback (timers.js: 789: 20) в tryOnImmediate (timers.js: 751: 5) at processImmediate [as _immediateCallback] (timers.js: 722: 5) Сбой приложения [nodemon] - ожидание изменений файла перед запуском ...

Как отправить токен на NodeJs

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...