Access-Control-Allow-Origin Policy

Thank U so much!!!It bothered me for two days.
Ur solution works!:grimacing:

2 Likes

I actually still have the same problem. I have an express app and This is my cors config :

and here is my server.js

'use strict';
const express = require('express');
const serverLess = require('serverless-http');
const app = express();
const bodyParser = require('body-parser');
const router = express.Router();
const mailer = require('../mailer');
const cors = require('cors');


const allowedOrigins = ['http://localhost:3000',
  'https://www.supercode.co.za'];
app.use(cors({
  origin: function(origin, callback){
    // allow requests with no origin
    // (like mobile apps or curl requests)
    if(!origin) return callback(null, true);
    if(allowedOrigins.indexOf(origin) === -1){
      let msg = 'The CORS policy for this site does not ' +
        'allow access from the specified Origin.';
      return callback(new Error(msg), false);
    }
    return callback(null, true);
  }
}));
router.post('/api/contact', (req, res) => {
  // console.log(req);
  const {
    firstName = req.body.firstName,
    lastName = req.body.lastName,
    message = req.body.message,
    phone = req.body.phone,
    email = req.body.email,
    website = req.body.website,
    company = req.body.company,
  } = req.body;
  mailer.send({email, firstName, text: message, phone, website, company, lastName}).then(() => {
    res.sendStatus(200);
  }).catch((error) => {
    console.log(error);
    res.sendStatus(500);
  });
});

also i have this in my toml file netlify
[build]
command = “npm install && npm run build”
functions = “functions”
[[headers]]
# Define which paths this specific [[headers]] block will cover.
for = “/"
[headers.values]
Access-Control-Allow-Origin = "

@heshamelmasry77, you don’t have a value for the Access-Control-Allow-Origin header in your example, just empty quotes. You may want to enter a domain or * in there. Also, are you trying to request a file from your node server or from your netlify site? you shared CORS settings on your server and on netlify so it’s not clear what the actual problem is. Please provide more details. Thanks.

For some reason it’s not working for me… I have both _headers and netlify.toml configured.

_headers
/*
Access-Control-Allow-Origin: *

netlify.toml
[[headers]]
for = "/*"
[headers.values]
Access-Control-Allow-Origin = "*"

It does work when I check it, but the CORS is still blocking googletagmanager.com

@andylemaire Adding that header to your assets that load from Netlify will not have any effect on assets loaded from other places.

In my last response, I asked if you were trying to load a file from your server or netlify site and you didn’t provide any additional details so I still don’t know which file is giving you the CORS error.

@futuregerald I’m trying to load Google Tag Manager on my website hosted on Netlify.

@futuregerald also, this used to work so I don’t understand why it’s not working anymore now…
All I did was adjust my headers quite much.

edit: alright I fixed it, seems like I forgot something in the CSP, nothing to do with the Access-Control-Allow-Origin.

1 Like

What was it? I have a similar problem and have been following your steps here without success.

@andylemaire - yes, please do tell us what you came up with for this!

@shkarlsson @perry I added all these to my CSP, not sure which was the blocking one but this made it work. So I’d compare it to yours…

connect-src https://www.google-analytics.com;
script-src https://www.googletagmanager.com https://www.google-analytics.com https://ssl.google-analytics.com https://www.googleadservices.com https://googleads.g.doubleclick.net;

1 Like

Thank you so much! It worked for me as well!

1 Like

I tried with this in my react app by creating the netlify toml file and does not work:
my netlify toml code is

  # Define which paths this specific [[headers]] block will cover.
  for = "/*"
    [headers.values]
    Access-Control-Allow-Origin = "*"```

I removed the redirect part because i dont have /index.html 
please could you help me?![Screenshot from 2020-08-23 12-21-18|690x388](upload://nmmiW1bALgVhjxNrZbjcCTNUkxO.png)

Hey @Karem1986,
Could you please share a Netlify URL so we can take a look?

And just to make sure, does your full netlify.toml match this?

[[headers]]
   for = "/*"
   [headers.values]
      Access-Control-Allow-Origin = "*"

Hi, I’m having the same issue, I’m using Gatsby + DatoCMS

At first this worked for me, but now it is not

[[headers]]
 # Define which paths this specific [[headers]] block will cover.
  for = "/*"
    [headers.values]
    Access-Control-Allow-Origin = "*"

this is the error I’m getting on my branch deploy
Access to fetch at 'https://site-api.datocms.com/docs/site-api-hyperschema.json' from origin 'https://dev.uthru.io' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:8000' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

and this is toml file

    [build]
      functions = "functions/"

    [[redirects]]
      from = "/app/*"
      to = "/app"
      force = false
      status = 200

    [[headers]]
     # Define which paths this specific [[headers]] block will cover.
      for = "/*"
        [headers.values]
        Access-Control-Allow-Origin = "*"

Hi, @tad1693NS. To troubleshoot this we need to be able to test. What is a URL where we will be able to see this error?

You can post that URL publicly or private message (PM) that to one of our support staff. I’ve confirmed that PMs are enabled for your community login. Note, that only one person can see the PM and this will likely mean a slower reply than posting the information publicly. Please feel free to reply to however you prefer though.

Have you resolved the CORS issue? I’m having exact issue even I have the headers section in my toml file

Yes I did, eventually, it was a cache problem with DatoCMS

Here is my toml file

[build]
  publish = "site"
  functions = "lambda"
  Command = "npm run build:lambda"
[[headers]]
  for = "/*"
    [headers.values]
    Access-Control-Allow-Origin = "*"

but I’m still running into CORS error:

reimburse:1 Access to XMLHttpRequest at ‘https://peaceful-****.netlify.app/.netlify/functions/uploadFiles’ from origin ‘http://localhost:8080’ 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.

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