Ask coding questions

← Back to all posts
Replit Database - How do I return the list of keys as JSON?
Seven7Four4 (20)

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!

Comments
hotnewtop
Coder100 (18818)

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 });
  }
})
Seven7Four4 (20)

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

Coder100 (18818)

also what does it return instead? @Seven7Four4

Seven7Four4 (20)

@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.

Coder100 (18818)

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

Coder100 (18818)

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

Seven7Four4 (20)

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

Seven7Four4 (20)

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