简体   繁体   中英

How to pass props from a pre-filled React input form back to Express?

In my React App, I've created a simple support form using Express & Sendgrid. The post request works with an input form like this:

support.jsx

  <form method="POST" action="http://localhost:4000/support">
    <div>
      <label htmlFor="email">
        <div>Email:</div>
        <input type="text" name="name" required />
      </label>
    </div>

support.js (Express)

app.post('/support', (req, res) => {
  const { email = '', name = '', message = '' } = req.body

  mailer({ email, name, text: message }).then(() => {
    console.log(`Sent the message "${message}" from <${name}> ${email}.`);
    res.redirect('/#success');
  }).catch((error) => {
    console.log(`Failed to send the message "${message}" from <${name}> ${email} with the error ${error && error.message}`);
    res.redirect('/#error');
  })
})

This works and I am able to send an email when I manually type in the email. However, since this app has authenticated users, I am now trying to pass the email address of the current user in the input field as shown in this StackOverflow answer:( How do I programatically fill input field value with React? ).

The props for currentUser.email is set in App.js and works in other places throughout the app.

SupportForm.jsx updated

      <label htmlFor="email">
        <div className="label-content">Email:</div>
        <input type="email" name={props.currentUser.email} placeholder={props.currentUser.email} disabled />
      </label>

support.js (Express) updated

const sgMail = require('@sendgrid/mail');
const { Router } = require('express');
const { User } = require("../models");
const supportRouter = Router();

  supportRouter.post('/support', async (req, res) => {
    
    try {
    const email = await User.findOne({email: req.body.email});
    const { message = '' } = req.body
    
    sgMail.setApiKey('PROCESS.ENV.SG');
   
    const msg = {
        to: 'me@gmail.com',
        from: email,
        subject: 'Support Request',
        text: message
    }

...// omittedcode ...

  module.exports = {
    supportRouter,
  };

This also works ( {"message": "success"} ), however when I get check the email, it is sent from the same email in to: of const msg resulting in a spoof email.

How do I post the current users' email to the request? I'm a bit lost at this point so thanks in advance for pointing me in the right direction.

Did you try logging req.body.email to check the problem was back-end related? I believe your email variable in your controller is undefined which leads sendgrid to default to using the same address for from and to . But it's hard to know with so little information.

I hope that helps!

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