_headers / .toml / CORS

answered
#1

Hello!

Does it take time for the _headers or netlify.toml file to begin using the headers in those files? I see content updates immediately, but the changes in the _headers file is not immediate.

This is the header file: https://github.com/rendall/api-cat/blob/deploy/_headers

According to ‘playground’ it is correct.

I deployed the same headers in the netlify.toml file, as weill. Other variables in the .toml file are seen by the site, so I know that it is deploying properly.

This is the function that I am attempting to access via javascript:
https://focused-elion-17290b.netlify.com/.netlify/functions/breed/

However, accessing it using fetch gives me no love:

fetch('https://focused-elion-17290b.netlify.com/.netlify/functions/breed/',
  {method:"GET"})
  .then((result) => result.json())
 .then(json => console.log("json", json))

Access to fetch at ‘https://focused-elion-17290b.netlify.com/.netlify/functions/breed/’ from origin ‘{everywhere}’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

But it is in both the _headers file and netlify.toml

#2

Okay! I may have solved this, and I will leave this here for anyone else struggling with this.

functions appear to have different headers than rest of the site! So, functions’ headers are affected by neither the _headers file nor the netlify.toml headers section.

According to https://www.netlify.com/docs/functions/

The callback works much like the same parameter in an AWS Lambda function. Your handler should use the callback to return either an error (as the first parameter) or a response object, such as:

{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "body": "..."
}

So, it is necessary to return headers along with the function!

Boom! Done.

2 Likes
#3

Hi, that’s correct! You do indeed return the desired headers in your callback function. :slight_smile:

1 Like