Skip to main content

Read and return HTTP status code

Read values from uri and return the associated status code

Javascript SDK

In order to test the development of CDB EdgeCompute application we will need some origin server that simulate some behaviour and return specific HTTP Code. This solution is an example to use the Javascript SDK:

addEventListener('fetch', event => {
const { request } = event;
const url = new URL(request.url);

if (url.pathname === '/favicon.ico') {
    return event.respondWith(new Response(null, { status: 204 }));
}

event.respondWith(handleRequest(request));
});

async function handleRequest(request) {
const encoder = new TextEncoder();
const url = new URL(request.url);
const parts = url.pathname.split('/').filter(Boolean);
const codeStr = parts[0];
const statusCode = (codeStr && /^\d{3}$/.test(codeStr))
    ? parseInt(codeStr, 10)
    : 500;

const message = `Statut dynamique choisi : ${statusCode}\nURL reçue : ${url.href}`;
console.log("Statut dynamique choisi :", statusCode);

return new Response(message, {
    status: statusCode,
    headers: {
    'Content-Type': 'text/plain; charset=utf-8'
    }
});
}