简体   繁体   中英

Sending info and variables between Client-Side and Server-Side

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.

On the client side there will be a form. That form will have an input field for the email address that should have some name name/id. When the form is submitted, that name id will be a part of the request object's body. Here's a link with more info

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()
    }
  })
}
})

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