#Simple node express server not serving routes, no errors

6 messages · Page 1 of 1 (latest)

glass star
#

very simple server.js file, this is my code,

the app runs locally but not on railway, no routes are served

const app = express();
const fs = require("fs");
const path = require("path");

app.get("/:key", (req, res) => {
    const key = req.params.key;
    const filePath = path.join(__dirname, "db.json");
    fs.readFile(filePath, (err, data) => {
        if (err) {
            console.error("Error reading file:", err);
            return res.status(500).json({ error: "Internal server error" });
        }

        let jsonData;
        try {
            jsonData = JSON.parse(data);
        } catch (err) {
            console.error("Error parsing JSON:", err);
            return res.status(500).json({ error: "Internal server error" });
        }

        if (!jsonData[key]) {
            console.error("Key not found in JSON data:", key);
            return res.status(404).json({ error: `Key "${key}" not found in data` });
        }

        res.json(jsonData[key]);
    });
});

app.get("/:key/:id", (req, res) => {
    const key = req.params.key;
    const id = req.params.id;
    const filePath = path.join(__dirname, "db.json");
    fs.readFile(filePath, (err, data) => {
        if (err) {
            console.error(`Error reading file from disk: ${err}`);
            return res.status(500).send(`Error reading file from disk: ${err}`);
        }
        let jsonData;
        try {
            jsonData = JSON.parse(data);
        } catch (parseErr) {
            console.error(`Error parsing JSON file: ${parseErr}`);
            return res.status(500).send(`Error parsing JSON file: ${parseErr}`);
        }

        if (!jsonData[key]) {
            console.error(`Key "${key}" not found in the JSON data.`);
            return res.status(404).send(`Key "${key}" not found in the JSON data.`);
        }

        const item = jsonData[key].find((item) => item.id === parseInt(id));

        if (!item) {
            console.error(`Item with id "${id}" not found in the key "${key}".`);
            return res
                .status(404)
                .send(`Item with id "${id}" not found in the key "${key}".`);
        }

        res.json(item);
    });
});

app.listen(3000, () => {
    console.log("Server started on port 3000");
});
arctic ermineBOT
#

To help others find answers, you can mark your question as solved via Right click solution message -> Apps -> ✅ Mark Solution

spiral sleetBOT
#

Project ID: f9302c62-de80-4dc2-86bb-1095312b9867

glass star
#

f9302c62-de80-4dc2-86bb-1095312b9867

gaunt urchin
glass star
#

this was exactly it, using process.env.PORT solved it. Ty