0

the chrome console returned this error "Form submission canceled because the form is not connected" on hitting the submit button, though nothing was returned in the IDE terminal. The react form is connected to a node js backend using express, nodemailer,cors, google api, dotenv and google-auth-library

const CLIENT_ID = process.env.CLIENT_ID
const CLIENT_SECRET = process.env.CLIENT_SECRET
const REDIRECT_URI = process.env.REDIRECT_URI
const REFRESH_TOKEN = process.env.REFRESH_TOKEN

const oAuth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)
oAuth2Client.setCredentials({refresh_token:REFRESH_TOKEN})

app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(cors())


app.post("/send_mail", cors(), async (req, res) => {

    const output = `
    <p>You have a new contact request</p>
    <h3>Contact Details</h3>
    <ul>  
      <li>Name: ${req.body.name}</li>
      <li>Email: ${req.body.email}</li>
      
    </ul>
    <h3>Message</h3>
    <p>${req.body.message}</p>
  `;

  try{
    const accessToken = await OAuth2Client.getAccessToken()
    

    const transport = nodemailer.createTransport({
        host: 'example.com',
        port: 465,
        secure: true,
        service: 'gmail',
        auth: {
            type: 'OAuth2',
            user: process.env.USERNAME,
            clientId: CLIENT_ID,
            clientSecret: CLIENT_SECRET,
            refreshToken: REFRESH_TOKEN,
            accessToken: accessToken

        }
    })

    await transport.sendMail({
        from: '"example Contact" <contact@example.com>',
        to: 'hey@gmail.com',
        subject: "test email",
        html: output
        
    })
} catch (error) {
    return error
}
    
})


app.listen(7000, () => console.log('Server started...'));

export default function ContactForm() {
  const [ sent, setSent ] = useState(false);
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [message, setMessage] = useState('');

  const handleSend = async (e) => {
        setSent(true)
        try {
            await axios.post("http://localhost:7000/send_mail", {
                name, email, message
            })
        } catch (error) {
            console.error(error)
        }
    }



  return (
    <>
        {!sent ? (
      <FormStyle onSubmit={handleSend}>
        <div className="form-group">
          <label htmlFor="name">
            Your Name
            <input
              type="text"
              id="name"
              name="name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              
            />
          </label>
        </div>
        <div className="form-group">
          <label htmlFor="email">
            Your Email
            <input
              type="email"
              id="email"
              name="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          </label>
        </div>
        <div className="form-group">
          <label htmlFor="message">
            Your message
            <textarea
              type="text"
              id="message"
              name="message"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
            />
          </label>
        </div>
        <button type="submit" >Send</button>
      </FormStyle>
        ) : (
          
<MailSentAnimation />
          
          )}
    </>
  );
}
mahnuel
  • 49
  • 9
  • Does this answer your question: https://stackoverflow.com/questions/66327333/error-form-submission-canceled-because-the-form-is-not-connected – tromgy Jan 27 '22 at 11:47
  • in my case, it is `handleSend` and adding the prevent default method, my code looks like this `const handleSend = async (e) => { e.preventDefault(); ...}`. The error cleared in the console though the form still doesn't actually submit. Not sure what to do next but if it's of any importance, the server at `localhost:7000` returns a **cannot Get/** – mahnuel Jan 27 '22 at 15:25
  • When you just try GET `localhost:7000`, it will not work because you don't have that route (`/`) defined. And your POST `/send_mail` route doesn't do anything with `res`. Do at least `res.send('ok')` or something like that after `sendMail`. – tromgy Jan 27 '22 at 22:40
  • I have effected all you suggested in the code. Added `app.get('/', cors(), async (req, res) =>{ res.send("this is working")` and `res.send('ok')` into the code. No error is being returned and `localhost:7000` now returns **this is working** . Yet, the messages are still not sent. I thought it was maybe because it was running on my local machine so i deployed it, but its still the same outcome. – mahnuel Jan 28 '22 at 08:12
  • I think I might have found a problem but I'm not sure how to solve it. I switched the google API service to Mailtrap instead to test code. It basically presented the same problem, no error returned but it doesn't actually send any message. So I used the credentials directly instead of passing it through dotenv and it worked. Not sure what to do because dotenv is already required in the code. – mahnuel Jan 28 '22 at 09:30

0 Answers0