Alex Cotton
Alex Cotton

Reputation: 3

How do I fix the CORS error on this React-hook-form?

I am having a problem with the Form Submission on the deployed site due to CORS error:

Access to XMLHttpRequest at 'https://url/api/contactFormSubmission' from origin 'https://differentUrl.vercel.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. url/api/contactFormSubmission:1

Failed to load resource: net::ERR_FAILED

I realize this error is due to the url´s not matching

But I still can´t seem to fix the problem, any help?

This is the code for the API form submission:

import nodemailer from 'nodemailer'

export default async (req, res) => {
  const {name, surname, companyName, email, numberOfEmployees, info, consent } = req.body;
  const  transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 465,
    secure: true,
    auth: {
      user: process.env.user,
      pass: process.env.pass
    }
  })

  try {
    const emailResponse = await transporter.sendMail({
      from: email,
      to: '[email protected]',
      subject: `Contact form submission from ${name}`,
      html: `<p>You have a new contact form submission</p><br>
      <p><strong>Name: </strong> ${name} </p><br>
      <p><strong>Surname: </strong> ${surname} </p><br>
      <p><strong>Company Name: </strong> ${companyName} </p><br>
      <p><strong>Email: </strong> ${email} </p><br>
      <p><strong>Number of Employees: </strong> ${numberOfEmployees} </p><br>
      <p><strong>Message: </strong> ${info} </p><br>
      <p><strong>Consent: </strong> ${consent} </p><br>
      `,
    })
    console.log(`Message sent`, emailResponse.messageId);
  } catch (err) {
    console.error(err);
  }

  res.status(200).json(req.body);

}

This is the Contact Form component code:

import React from 'react'
import { useForm } from 'react-hook-form'
import Link from 'next/link'
import axios from 'axios';
import { useRouter } from 'next/router'

function ContactForm(props) {
    const {register, handleSubmit, formState: { errors }, reset } = useForm();
    const router = useRouter()
    async function onSubmitForm(values) {
        let config = {
            method: 'post',
            url: `${process.env.NEXT_PUBLIC_API_URL}/api/contactFormSubmission`,
            headers: {
                'Content-Type': 'application/json',
            },
            data: values,
        }
        try {
            const response = await axios(config);
            if(response.status == 200) {
                reset()
                router.push('/');
            }

        } catch (err) {

        }

    };

  return (
    <div className='my-6 max-w-screen-lg mx-auto'>
        <form onSubmit={handleSubmit(onSubmitForm)}>

Upvotes: 0

Views: 634

Answers (1)

arnaspdk
arnaspdk

Reputation: 62

This is not being caused react-hook-form because it does not really have to do anything about API.

What is your CORS config for the backend?

To enable all CORS requests add app.use(cors())

Upvotes: 2

Related Questions