Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Last active July 17, 2021 15:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cferdinandi/7522908fd3796397abe6ff0b0c2c1df5 to your computer and use it in GitHub Desktop.
Save cferdinandi/7522908fd3796397abe6ff0b0c2c1df5 to your computer and use it in GitHub Desktop.
A middleman API boilerplate for Cloudflare Workers. https://workers.cloudflare.com/
addEventListener('fetch', function (event) {
event.respondWith(handleRequest(event.request));
});
// Allowed domain origins
var allowed = ['http://localhost:8000', 'https://your-website.com'];
/**
* Respond to the request
* @param {Request} request
*/
async function handleRequest(request) {
var headers = new Headers({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, HEAD, POST, OPTIONS',
'Access-Control-Allow-Headers': '*'
});
// If domain is not allowed, return error code
if (!allowed.includes(request.headers.get('origin'))) {
return new Response('Not allowed', {
status: 403,
headers: headers
});
}
// If the method is POST, get some values
var someVal = 'defaultValue';
if (request.method === 'POST') {
var body = await request.json();
someVal = body.someVal;
}
// Call the API
// Use API_KEY for wherever your API key should be passed in.
// That might be a header, or part of the URL itself
var resp = await fetch(`https://path-to-api.com?api-key=${API_KEY}&val=${someVal}`);
var data = await resp.json();
return new Response(JSON.stringify(data), {
status: 200,
headers: headers
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment