Search code examples
node.jssmtpnodemailer

node js server is setup correctly implemented still I am getting error that there's no connection to it(nodemailer SMTP method)


I set up a server with node js to send email to my gmail and although the server code is correct and all packages are installed (cors, body-parser, express) I am still getting error that there's no connection to it

error: enter image description here

server code:

const express=require('express')
const app =express();
const bodyParser=require('body-parser')
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
const cors=require('cors')

app.use(cors())

const nodemailer = require('nodemailer');

function sendEmail(link,email){
const transporter=nodemailer.createTransport({
    service:'gmail',
    auth:{
        user:'mai.sa2sa2@gmail.com',
        pass:''
    }
})


  // send mail with defined transport object
  let info =  transporter.sendMail({
    from: '"Fred Foo 👻" <foo@example.com>', // sender addressn
    to: email, // list of receivers
    subject: "qr Link", // Subject line
    text: link, // plain text body
    html: link, // html body
  });

  console.log("Message sent: %s", info.messageId);
}

app.post("/api/sendMail",(req, res)=>{
    console.log(req.body);
sendEmail(req.body.link,req.body.email)
})
app.listen(8080,()=>{
    console.log("server is running ");
})

and here's the function that should send the email:

sendToServer(email,score){
      axios({method: "POST", 
      url:"http://localhost:8080/api/sendMail", 
      data: {score:this.state.score,email:"mai.sa2sa2@gmail.com"
    }}).then((response)=>{
      if (response.data.status === 'success'){
        alert("Message Sent."); 
        this.resetForm()
      }else if(response.data.status === 'fail'){
        alert("Message failed to send.")
      }
     })
    }

Vs code giving "missing script": enter image description here


Solution

  • So I am guessing the file the contains the code is called app.js or index.js either way open package.json file and add this under scripts section

    {
       "server": "node src/server.js" // or whateverfilename you have for you node code "node src/filename.js"
    }