Access-Control-Allow-Origin Policy

This is something related to your functions, not the application. “The preflight request” is like verification a request make to the server to see if they have access to a particular resource (in this case your function https://peaceful-****.netlify.app/.netlify/functions/uploadFiles)

When you try to access your functions on your local machine it will go on CORS since both resources are in different locations, you need to add additional Headers to your response so it can communicate effectively with your application. You can read more about it here

Here is a snip of what I did on my functions to solve the problem

let HEADERS = {
  'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Origin',
  'Content-Type': 'application/json', //optional
  'Access-Control-Allow-Methods': 'POST, OPTIONS',
  'Access-Control-Max-Age': '8640'
}

//This solves the "No ‘Access-Control-Allow-Origin’ header is present on the requested resource."

HEADERS['Access-Control-Allow-Origin'] = '*'
HEADERS['Vary'] = 'Origin'

exports.handler = async function (event, context) {
  try {
    if (event.httpMethod === 'OPTIONS') {
      return { statusCode: '204', HEADERS }
    }
    if (event.httpMethod === 'POST') {
        const body = JSON.parse(event.body)
        //Your code goes here

       return {
         statusCode: 200,
         body: 'Success',
         HEADERS
       } 
 
    }
    return {
      statusCode: 401,
      HEADERS
    }
  } catch (e) {
    console.error(e)
    return {
      statusCode: 500,
      body: e.toString()
    }
  }
}

Here is a list of good resources that can help you understand better:

If you want to test your functions on your local machine I suggest using Netlify Dev. It will create a local server for you to run your functions

2 Likes