A template for kick starting a Cloudflare worker project.
index.js
is the content of the Workers script.
To generate using wrangler
wrangler generate projectname https://github.com/cloudflare/worker-template
Further documentation for Wrangler can be found here.
npm install -g @cloudflare/wrangler - old
npm install -g wrangler
wrangler generate serverless-api
wrangler login
- A link opens in browser then just do as it says and grant permission
wrangler whoami
- Paste the account id into wrangler.toml
wrangler deploy "index.js"
This will seamlessly deploy your api
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Respond with hello worker text
* @param {Request} request
*/
async function handleRequest(request) {
const { query } = await request.json()
return new Response(`Your response was ${query}`)
}
wrangler dev "index.js"
curl -H "Content-type: application/json" -d '{"query": "guitar"}' http://127.0.0.1:8787
$body = @{
query = "guitar"
} | ConvertTo-Json
Invoke-WebRequest -Uri "http://127.0.0.1:8787" -Method POST -Body $body -Headers @{
"Content-Type" = "application/json"
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
/**
* Respond with Unsplash photos using the Unsplash API
* @param {Request} request
*/
async function handleRequest(request) {
const CLIENT_ID = ""; // Replace with your Unsplash API Client ID
try {
const resp = await fetch("https://api.unsplash.com/photos", {
headers: {
Authorization: `Client-ID ${CLIENT_ID}`,
},
});
if (!resp.ok) {
throw new Error(`Unsplash API request failed with status: ${resp.status}`);
}
const data = await resp.json();
return new Response(JSON.stringify(data), {
headers: {
'Content-type': 'application/json',
},
});
} catch (error) {
return new Response(`Error: ${error.message}`, {
status: 500,
headers: {
'Content-type': 'text/plain',
},
});
}
}
wrangler dev "index.js"
Invoke-WebRequest -Uri "http://127.0.0.1:8787"
wrangler secret put CLIENT_ID
wrangler publish "index.js"
- Now we can access https://serverless-api.username.workers.dev