I've been working on an expressJS script that includes a mongoDB fetch. My objective is to create an API that displays my JSON-based test list on the /api/testlist route.
When I try to access the index page, everything seems to be working fine. However, I'm facing issues with the API route.
It's quite strange because I can reach 'IP + port/api/testlist', but if I use my domain address instead, I get a 404 error. Interestingly, the index page loads fine with the domain address.
Below is the script I'm using:
const { MongoClient } = require('mongodb');
const express = require("express");
const app = express();
const port = 3000;
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
try {
client.connect();
console.log('Connected to MongoDB');
} catch (err) {
console.error('Error connecting to MongoDB:', err);
}
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.get("/api/testlist", async (req, res) => {
try {
const collection = client.db('test').collection('test');
const result = await collection.find({}).toArray();
if (result.length > 0) {
res.json({ result });
} else {
res.json({ message: 'items not found'});
}
} catch (err) {
console.error("Error querying MongoDB:", err);
res.status(500).send("Error querying the database");
}
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
I've attempted to configure the nginx server config and the mongoDB config, but without success.
There seems to be something off in the script that I haven't been able to pinpoint yet. Perhaps there's something missing or overlooked.