I wanted to implement a rudimentary leaderboard to my game on Repl.it, so I created a node.js backend. This is what I have on the backend:
const express = require('express');
const Client = require('@replit/database');
const db = new Client();
const cors = require('cors');
const bcrypt = require('bcrypt');
const bodyParser = require('body-parser');
const server = express();
server.use(cors());
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.get('/', (req, res) => {
res.send('Online');
});
server.post('/leaderboard', async (req, res) => {
const m = await db.get('leaderboard');
m.push({
score: parseInt(req.body.score, 10),
time: new Date()
});
m.sort((a, b) => b.score - a.score);
await db.set('leaderboard', m);
res.send(req.body);
});
server.get('/leaderboard', async (req, res) => {
const leaderboard = await db.get('leaderboard');
res.json(leaderboard);
});
server.listen(3000);
But whenever I try to POST, I get the following error:
(node:344) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'push' of null
(node:344) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag
--unhandled-rejections=strict
(see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:344) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
And if I try to GET, res
returns null
- probably since I'm not pushing anything when doing POST.
Why is this happening, and how do I fix it?