This is the api.js module which creates a test route:
'use strict';
module.exports = function (app) {
console.log("before route creation");
app.get("/api/test", (req, res) => {
res.send("it worked");
});
console.log("routes created");
};
In the server.js file, I am importing this module as apiRoutes
. Then, I am calling it inside an async function.
const databaseConnection = async (apiRoutes, app) => {
try {
await mongoose.connect(`mongodb+srv://replitUser:${process.env.DB_PW}@issuetracker.pbbm6.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`);
console.log("db connection successful");
//Routing for API
console.log("apiRoutes called");
apiRoutes(app);
} catch (err) {
console.log("an err occurred", err);
}
}
databaseConnection(apiRoutes, app);
// apiRoutes(app);
The strings "before route creation"
and "routes created"
are logged to the console. However, the route does not seem to work, although no errors are occurring.
If I call apiRoutes
outside of the async function, like here:
const databaseConnection = async (apiRoutes, app) => {
try {
await mongoose.connect(`mongodb+srv://replitUser:${process.env.DB_PW}@issuetracker.pbbm6.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`);
console.log("db connection successful");
//Routing for API
// console.log("apiRoutes called");
// apiRoutes(app);
} catch (err) {
console.log("an err occurred", err);
}
}
databaseConnection(apiRoutes, app);
apiRoutes(app);
...it will create the test route successfully.
I've tried to create the route directly inside of the async function and not in a new module, and it changed nothing, the route is still not created.
const databaseConnection = async (apiRoutes, app) => {
try {
await mongoose.connect(`mongodb+srv://replitUser:${process.env.DB_PW}@issuetracker.pbbm6.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`);
console.log("db connection successful");
//Routing for API
// console.log("apiRoutes called");
// apiRoutes(app);
app.get("/api/test", (req, res) => {
res.send("it worked");
});
} catch (err) {
console.log("an err occurred", err);
}
}
databaseConnection(apiRoutes, app);