Created
May 10, 2020 20:00
-
-
Save cheapsteak/dfbec27ab7c5e7d74816272dfeae7352 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const netlifyHost = 'my-app.netlify.app'; | |
const shouldAllowCORS = (origin) => { | |
if (/http\:\/\/localhost:/.test(origin)) { | |
return true; | |
} | |
if (origin === (`https://${netlifyHost}`) || (new RegExp(`--${netlifyHost.replace(/\./g, '\.')}`)).test(origin)) { | |
return true; | |
} | |
return false; | |
} | |
/** | |
* Responds to any HTTP request. | |
* | |
* @param {!express:Request} req HTTP request context. | |
* @param {!express:Response} res HTTP response context. | |
*/ | |
exports.myHandler = (req, res) => { | |
const origin = req.headers.origin; | |
if (shouldAllowCORS(origin)) { | |
res.set('Access-Control-Allow-Origin', origin); | |
if (req.method === 'OPTIONS') { | |
res.set('Access-Control-Allow-Methods', 'POST'); | |
res.set('Access-Control-Allow-Headers', '*'); | |
res.status(204).send(''); | |
return; | |
} | |
} | |
// ... rest of handler | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment