so I have an express.js server, I don’t quite understand how I can send and receive
I have (for example) an input for someone to write his email , I want the email to be sent to the server, validated, and then an email function sends an email to that user, However, my issue is that I don’t know how to pass the email variable from client to the server, and I don’t know how to trigger the email function as soon as the server validates the email either.
The only thing that I know to do with an express server is just routing Pages from. I tried AJAX but I think that’s overkill because I don’t understand it well and because its made to load data in a website without a reload so it has different kind of purpose.
Advertisement
Answer
Lets say your form is something like this:
<form action="/subscribe" method="post">
<input type="text" name="email"/>
<input type="submit" />
</form>
In your express server you’d do something like this:
router.post('/subscribe',(req,res,next)=>{
if(!emailValidator(req.body.email)){
// I would do email validations client side to but if you
// want to do server side send some html saying the email is invalid
res.sendFile(invalidEmail.html)
}
else{
//I assume you have some script for sending email. I'll use nodemailer cuz its the first
//module I found
let sender = 'emailbot@website.com'
let transporter = nodemailer.createTransport({
service:'gmail',
auth:{
user:sender,
pass:'password'
}
})
let mailOptions = {
from: sender,
to: req.body.email,
subject:'New sign up',
text:'Thanks for subscribing'
}
transporter.sendMail(mailOptions,function(error,info){
if(error){
// do somehting
console.log(error)
}
else{
console.log('Sent new user email')
req.next()
}
})
}
})