← Back to Community
Replit Database - How do I return the list of keys as JSON?
Profile icon
Seven7Four4

Hello there,
I'm trying to make a submit system in Express, but I need it to be returned as a JSON.
I tried this:

var _final_res; var ctr; var express = require('express') var app = express() const bodyParser = require('body-parser'); app.use(bodyParser()); app.get('/getDataBase', function(req, res) { if (req.body.password == process.env.password && req.body.user == process.env.user){ db.list().then(keys => {keys.forEach(function(a){ ctr++; db.get(a).then(value => { _final_res=_final_res + a + ': "' + value + '",\n';}); if (ctr === keys.length) { res.json({_final_res}) } })}); } })

but everytime i make a GET request to /getDataBase, it doesn't return anything. Could anyone help?
Thanks!

Voters
Profile icon
Seven7Four4
Comments
hotnewtop
Profile icon
Coder100

you must put _final_res inside the .then function. This is because res.json will happen before db.get, as db.get takes some time to complete, so like this:

db.get(a).then(value => { _final_res = ...; if (ctr === keys.length) { res.json({ _final_res }); } })
Profile icon
Seven7Four4

@Coder100 Hmmm... still does not work for me. It still doesn't return _final_res when I make a request.

Profile icon
Coder100

can i see your code @Seven7Four4

Profile icon
Coder100

also what does it return instead? @Seven7Four4

Profile icon
Seven7Four4

@Coder100 it doesn't return anything. It just keeps on loading, no message says "XHR Request/Fetch finished loading" and when I navigate to the page with the password and user, it just keeps on loading.

Profile icon
Seven7Four4
Profile icon
Coder100

oh i see, your db must have had an error, or ctr == keys.length was never met. @Seven7Four4

Profile icon
Coder100

makes sense, you defined ctr outside of the request body, that's not good. Put it inside the request body so it is set to 0 each time. (which you also didn't do, you only did var a; so a++ will be NaN) @Seven7Four4

Profile icon
Seven7Four4

@Coder100 Is it possible to fix it? Is there a way to return list as JSON?

Profile icon
Seven7Four4

@Coder100 kinda confused, could you send me the full code as a reference?