简体   繁体   中英

I'm trying to send an email with node, nodemon, express and dotenv

I'm trying to send a email verification with a token verification, the code doesn't mark me any error, but when I use my route, it does not work, so I'm not sure why, All these are into a API development, I'm gonna leave the code.

First I'm leaving my server index:

//IMports
const express =  require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cors = require("cors");
const path = require("path");
const NODE_ENV = process.env.NODE_ENV || 'development' 


require('dotenv').config({path:__dirname+'/config.env'})

// Init app
const app = express();

// settings
app.set("port", process.env.PORT || 3000)
app.use(cors({
 origin: process.env.PORT || 3003 //cors permite el uso de react
}))

app.use(morgan('dev'))//morgan debe dar información porcada petición



// middlewares
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

//routes
app.get("/", (req, res) => {
    res.send("welcome to api kiral")
});

app.use(require('./routes/Task.routes'))
app.use(require('./routes/Team.routes'))
app.use(require('./routes/Register.routes'))
app.use(require('./routes/Prueba.routes'))



// Start server
app.listen(app.get("port"), () => {
    console.log(`Server on port ${app.get("port")}`);
});

How you can see it is calling an config.env with the path method so now I'll show you that document:

CLIENT_URL=https://localhost:3000
JWT_ACCOUNT_ACTIVATION = 6f192f5a5dfe77993d390ec486aa00317c8e6f63f7661181313eb551f7a7b4c34c60641f57e94ccabdd8d5be2fe07dfda21651473e0a39
JWT_SECRET = 7643d1abcc6b9b04a6e50510953a76abcb5d72e2fe3e04a074dd9871e390c6d1214db7af574c0afc82d292aa96217aa647a88d3cc8accd4
JWT_RESET_PASSWORD = 192366c6415126025d84ed1953a76abcb5d72e2fe3e04a074dd9871e390c6d1214db7af574c0afc82d292aa96217aa647a88d3cc8accd4
EMAIL_FROM = ree@grro.com
MAIL_KEY = SG.G-2g7t60To6KMnXJEpg23aALV1CgKGOLiRGkNEbbv10hI

The mail key is because I'm using SendGrid/mail, so in this case, all these env variables is working.

How you can see on the index document I have routes, that is the next document.

const { Router } = require('express')
const router = Router();
const authController = require("../controllers/Register.controller");


//TAREAS

//GETS
router.get("/register", authController.getAuth)
router.get('/register/:email', authController.getAuths)


module.exports = router;

And at least, I have the code in charge of sending the email when it receives the user email.

const expressJwt = require('express-jwt')
const _ =require('lodash')
const { OAuth2Client } = require('google-auth-library')
const fetch = require('node-fetch')
const {validationResult} = require('express-validator')
const jwt = require('jsonwebtoken')
//Esto es para obtener el error de la  base de datos, se puede personalizar para hacerlo amigable.
const { errorHandler} =require('../helpers/dbErrorHandling')
//el siguiente const se usará para enviar correos
const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(process.env.MAIL_KEY)

const pool = require('../database/connection')


class AuthController {
    async getAuth (req, res) {
        const result = await pool.query('select User_email from user');

        res.json({
            code: 200,
            message: "Prueba realizada con éxito",
            data: result
            
        });
    }


    async getAuths(req, res) {
    const email = (req.params.email);
    let sql = `select User_email from user where User_email = ${email}`;
    const mail = poo.query(sql);

    if(email.length = 0) {
        return res.json({
            code: 404,
            message: "Equipo no encontrado",
            data: [],
        })

    }else{
 

    //generate token

    const token = jwt.sign(
        {email}, 
         process.env.JWT_ACCOUNT_ACTIVATION,
        {expiresIn: '1440m' }
    )

    const emailData = {
      from: process.env.EMAIL_FROM,
      to: email,
      subject: 'Account activation link',
      html: `
                <h1>Please use the following to activate your account</h1>
                <p>${process.env.CLIENT_URL}/register/${token}</p>
                <hr />
                <p>This email may containe sensetive information</p>
                <p>${process.env.CLIENT_URL}</p>
            `
    }

    sgMail.send(emailData).then(sent => {
        return res.json({
            message: `el email se ha enviado a ${email}`
        })
    }).cath(err => {
        return res.status(404).json({
            error: errorHandler(err)
        })
    })

    }

        
    }

}


const authController = new AuthController();
module.exports = authController;

I'm new working with APIS, and all looks fine, all the libraries coded are installed so that's right, and the code looks fine for me.

Looks like the misspelling of catch as Cath may cause you some trouble along with the other things I'd commented, take a look and see if fixing those up helps you out!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM