Return JSON

In this example, an Edge Function is used to generate a JSON object, and the JSON object is accessed and previewed from a browser.

Sample Code

const data = {
  content: 'hello world', 
};

async function handleRequest(request) {
  // Convert the JSON object to the String format.
  const result = JSON.stringify(data, null, 2);

  return new Response(result, {
    headers: {
      'content-type': 'application/json; charset=UTF-8',
    },
  });
}

addEventListener('fetch', event => {
  return event.respondWith(handleRequest(event.request));
});

Sample Preview

In the address bar of the browser, enter a URL that matches a trigger rule of the Edge Function to preview the effect of the sample code. 

2.png

References

  1. Runtime APIs: addEventListener
  2. Runtime APIs: Response