Access-Control-Allow-Origin Policy

Hi there,

I am trying to access json resources deployed to a standard netlify site - but getting:

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

From the SPA when I make a request to the json file.

I am trying to formulate a _headers file to enable Cors - but having difficulty in getting this to work, and not sure this is in fact the correct approach.

I can see that the files are there as a standard browser request is retrieving them.

Any advice greatly appreciated!

Regards
E.

1 Like

Found the solution: this netlify.toml file will do the trick:

# The following redirect is intended for use with most SPAs that handle
# routing internally.
[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200

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

great find and thanks so much for sharing it with us! Netlify’s tech support would have given you a very similar answer :slight_smile:

If you’re using _headers that would look like this instead:

/*
  Access-Control-Allow-Origin: *

and the main gotcha is that that needs to be sitting next to index.html after your build completes, rather than in the root of your repo like netlify.toml

3 Likes

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