use D1 DB in worker (no wrangler etc, just JS)

hey there, noobie here. There are multiple tutorials online how to set up the D1 DB with a worker using wrangler, nodejs etc., however i just want to be able to use all the db related stuff within my js file, so no typescript. I went ahead and added the database via DB Database bindings in the settings of the worker, however any request i do in js returns empty data:
const { results } = await env.DB.prepare('SELECT * FROM user').all();
const json = await Response.json(results);
const jjson = JSON.stringify(json);
console.log(jjson);
const { results } = await env.DB.prepare('SELECT * FROM user').all();
const json = await Response.json(results);
const jjson = JSON.stringify(json);
console.log(jjson);
and yes, the DB is called user, the environment variable in the settings is DB. Am i missing something?
7 Replies
kian
kian12mo ago
Response.json is a static method to return a Response. That isn't something you can stringify.
Spuckwaffel
SpuckwaffelOP12mo ago
oh i see. how can i get the db result as a string?
kian
kian12mo ago
Just remove the const json line Stringifying results is all you need to do
Spuckwaffel
SpuckwaffelOP12mo ago
awesome! Thank you very much.
kian
kian12mo ago
If you're trying to return it to the user, you can do return Response.json(results) from your fetch handler return Response.json(obj) is basically return new Response(JSON.stringify(obj))
Spuckwaffel
SpuckwaffelOP12mo ago
alright, thanks!
Hello, I’m Allie!
Plus a content-type header
Want results from more Discord servers?
Add your server