CORS Error -- Access to fetch

This has been an ongoing issue with my site for some time now. I had a solution to it before and had no issues but recently it has popped back up again with my post call to my function endpoint.

This my lambda function which accepts a json request object which uses it to interact with an smtp request

const nodemailer =  require('nodemailer');

require('dotenv').config()

exports.handler = async (event, context) => {
    // const headers = {
    //   'Content-Type': 'application/json',
    //   /* Required for CORS support to work */
    //   'Access-Control-Allow-Origin': '*',
    //   'Access-Control-Allow-Methods': 'POST',
    //   'Access-Control-Allow-Headers': 'Content-Type',
    //   /* Required for cookies, authorization headers with HTTPS */
    //   'Access-Control-Allow-Credentials': trued
    // };
    const request = JSON.parse(event.body);  

    const validation = {
      name: request.name.length > 0,
      email: /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(request.email),
      message: request.message.length > 6 && request.message.length < 1001
    }

    const isValid = Object.keys(validation).every(field => field);

    if(!isValid) {
      return  {
        statusCode: 400,
        // headers,
        body: JSON.stringify({
          response: "Your request failed validation. Please try again in the next few moments",
        })
      }
    }

    let transporter = nodemailer.createTransport({
      host: process.env.SMTP_DOMAIN,
      port: process.env.SMTP_PORT,
      secure: true,
      auth: {
            user: process.env.SMTP_USERNAME,
            pass: process.env.SMTP_PASSWORD
      }
    })

    

    transporter.verify(function(error, success) {
      if (error) {
        return {
          statusCode: 503,
          // headers,
          body: JSON.stringify({
            response: "Uh oh! It looks like the messaging service is not available. Please try again later or reach out to me personally."
          })
        }
      } else {
        console.log("Server is ready to take our messages");
      }
    });

    let info = await transporter.sendMail({
      from: `"Portfolio Contact Form" <${request.email}>`,
      to: process.env.EMAIL_TO,
      subject: request.name,
      text: request.message
    })

    return info.response == "250 Great success" ? {
      statusCode: 200,
      // headers,
      body: JSON.stringify({
        response: "Your message has been successfully received!",
      })
    } : {
      statusCode: 500,
      // headers,
      body: JSON.stringify({
        response: "Hmmm... something went wrong while sending your message. Try back at a later time or email me personally"
      })
    }
  }

And my client request

const api_address = '@@api_address/.netlify/functions'

const postContactMessage = async (data) => {
    return await fetch(`${api_address}/contact`, { 
          method: 'POST', 
          body: JSON.stringify(data), 
          headers: {
            'Content-Type': 'text/plain',
            // 'Content-Type': 'application/x-www-form-urlencoded',
          }
        });
}

As you can see, I originally hardcoded a header to attach to the response to try to resolve the cors issue in the past. However, when a user attempts to send a contact message to the endpoint, the server picks up the request, sends a response, and the browser rejects the response object.

image

I understand what the issue is but I don’t quite undestand how to resolve the issue. I’ve tried uncommented the header and adding it with the response, and making a series of adjustments on my request object but no avail.

The solution maybe quick and easy but I’m at a point of befuddlement that it doesn’t look apparent to me.

Thanks to everyone who is reading this and taking time out of their day to help me with this :slight_smile:

Dan

Hi,

Is the function deployed on the same deploy that you are calling it from? Is there a reason you aren’t calling it from the domain that it’s deployed under? If you do so, you won’t hit that error. Try using a relative path like /.netlify/functions rather than hardcoding the address of a specific deploy URL and then calling that same code from your production site under a different domain.