AndyJessop
AndyJessop
CDCloudflare Developers
Created by Farwalker3 | Rogues on 4/1/2024 in #workers-help
Fetching From D1 using Workers
I think the best thing here is for you to take a look at this page, and follow along to ensure that you have the worker setup correctly. The function I gave you was just following your original code (e.g. using fetchAllData), but you will need to call that from inside the fetch function detailed on the docs page I just linked.
5 replies
CDCloudflare Developers
Created by Farwalker3 | Rogues on 4/1/2024 in #workers-help
Fetching From D1 using Workers
I think you'll want something like this:
async function getAllData(env) {
try {
const result = await env.DB.prepare('SELECT * FROM name_of_your_table').all();

return new Response(JSON.stringify(result.results), {
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
return new Response('Internal Server Error', { status: 500 });
}
}
async function getAllData(env) {
try {
const result = await env.DB.prepare('SELECT * FROM name_of_your_table').all();

return new Response(JSON.stringify(result.results), {
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
return new Response('Internal Server Error', { status: 500 });
}
}
5 replies