Blocked by CORS policy

Hi,

I am currently trying to send email via sendgrid on contact us form, below is the contact us form:

But it gives this error in console when click submit button:

Access to XMLHttpRequest at ‘https://api.sendgrid.com/v3/mail/send’ from origin ‘my domain’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The ‘Access-Control-Allow-Origin’ header has a value ‘https://sendgrid.api-docs.io’ that is not equal to the supplied origin.```


import React, { useState } from 'react';
import sgMail from '@sendgrid/mail';

const ContactFormSection = () => {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    subject: 'Course', 
    message: '',
    school: '',
  });

  const handleSubmit = async (e) => {
    e.preventDefault();

    const message = {
      to: 'email', // Replace with your own email address
      from: 'email,
      subject: 'hello world',
      html: `
        <p><strong>Name:</strong> ${formData.name}</p>
        <p><strong>Email:</strong> ${formData.email}</p>
        <p><strong>School:</strong> ${formData.school}</p>
        <p><strong>Message:</strong> ${formData.message}</p>
      `,
    };

    try {
      sgMail.setApiKey('MY SENDGRID API KEY'); // Set your own SendGrid API key
      await sgMail.send(message);
      alert('Email sent successfully!');
    } catch (error) {
      console.error(error);
      alert(`Failed to send email: ${error.message}`);
    }
  };

  const handleInputChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  return (
    <div className="contact-form">
      <form onSubmit={handleSubmit}>
        <div className="row">
          <div className="col-xl-6">
            <div className="contact-from-input mb-20">
              <input
                type="text"
                placeholder="Name"
                name="name"
                value={formData.name}
                onChange={handleInputChange}
              />
            </div>
          </div>
          <div className="col-xl-6">
            <div className="contact-from-input mb-20">
              <input
                type="text"
                placeholder="Email"
                name="email"
                value={formData.email}
                onChange={handleInputChange}
              />
            </div>
          </div>
          <div className="col-xl-6">
            <div className="contact-select">
              <select
                className="mb-20"
                name="subject"
                value={formData.subject}
                onChange={handleInputChange}
              >
                <option value="Course">Course</option>
                <option value="Financial Aid">Financial Aid</option>
                <option value="Payment">Payment</option>
                <option value="Information">Information</option>
              </select>
            </div>
          </div>
          <div className="col-xl-6">
            <div className="contact-from-input mb-20">
              <input
                type="text"
                placeholder="School (optional)"
                name="school"
                value={formData.school}
                onChange={handleInputChange}
              />
            </div>
          </div>
          <div className="col-xl-12">
            <div className="contact-from-input mb-20">
              <textarea
                placeholder="Message"
                name="message"
                value={formData.message}
                onChange={handleInputChange}
              ></textarea>
            </div>
          </div>
          <div className="col-xl-2 ">
            <div className="cont-btn mb-20">
              <button type="submit" className="cont-btn">
                Submit
              </button>
            </div>
          </div>
        </div>
      </form>
    </div>
  );
};

export default ContactFormSection;

Are you trying to send this from a front-end/client-side React application?

This is not how it is intended to work (AFAIK) rather from a server/-less function.

@jasiqli Yes, i am trying to send it in gatsby app front-end/client-side.

As mentioned I’m fairly certain that won’t work. You’ll need to set up a function.

Also trying to send it client-side would expose the API to everyone that uses the site which would then allow anyone to use it to send email via your account.

See also

Thank you for the reply.

I have now added a function but i get this error:

This function has crashed
An unhandled error in the function code triggered the following message:

ReferenceError - SG is not defined

Stack trace
ReferenceError: SG is not defined
    at Object.<anonymous> (/var/task/functions/sendEmail.js:2:18)
    at Module._compile (node:internal/modules/cjs/loader:1165:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1219:10)
    at Module.load (node:internal/modules/cjs/loader:1043:32)
    at Function.Module._load (node:internal/modules/cjs/loader:878:12)
    at Module.require (node:internal/modules/cjs/loader:1067:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/var/task/sendEmail.js:1:18)
    at Module._compile (node:internal/modules/cjs/loader:1165:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1219:10)
Connection details
Netlify internal ID: 01GWF8YPE231NJD9V9Y0RXYNSK
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

exports.handler = async (event) => {
  try {
    const { name, phone, email, subject, message } = JSON.parse(event.body);

    const msg = {
      to: 'xxx',
      from: 'xxx',
      subject: subject,
      text: `Name: ${name}\nPhone: ${phone}\nEmail: ${email}\n\nMessage: ${message}`,
    };

    await sgMail.send(msg);

    return {
      statusCode: 200,
      body: JSON.stringify({ message: 'Email sent successfully' }),
    };
  } catch (error) {
    console.log(error);
    return {
      statusCode: 500,
      body: JSON.stringify({ error: 'Error occurred while sending email' }),
    };
  }
};

The error simply means that somewhere in your code, you’re trying to access a variable called SG but it’s not defined. In your code snippet, I don’t see it anywhere. So, it could be coming from your dependencies.