Home > Back-end >  Setting up routers for my node.js project
Setting up routers for my node.js project

Time:04-19

So i am running into quite a few problems with how i am setting up my routes for my node.js app

here is my app.js and how i am calling the route

const express = require("express");
const bodyParser = require("body-parser");
const app = express();
require('dotenv').config()
const passport = require('passport')
const flash = require('express-flash')
const session = require('express-session')
const initializePassport = require('./passport-config')


const saltRounds = 10;
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static("public"));
// app.use('/public', express.static(__dirname   "/public"))
app.use(flash())
app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())


//Routes

// app.use(require('./routes'));
require('./routes/index.js')(app, passport, bcrypt, checkAuthenticated, checkNotAuthenticated, dbSize, saltRounds, User, setupDb);
require('./routes/dashboard.js')(app, passport, checkAuthenticated, checkNotAuthenticated, User, User_database, dbSize, Db_size, setupDb);
require('./routes/db.js')(app, passport, checkAuthenticated, checkNotAuthenticated, User, dbSize, User_database, Db_size, Db_tablespace, setupDb);
//GETS and POSTS


app.get('/logout', function (req, res) {

  req.logout();
  res.redirect("/");

});

app.use((req, res) => {
  res.status(404).render('404');
});
here's one of my routes db.js

var express = require('express');
var router = express.Router();
const Db_size = require('../db/models/db_size')
const Db_tablespace = require('../db/models/db_tablespace')

module.exports = (app, passport, checkAuthenticated, checkNotAuthenticated, User,dbSize,User_database,Db_size,Db_tablespace,setupDb) => {

    
    router.get('/:id/db_size', checkAuthenticated, async function (req, res) {
        const id = req.params.id;
        try {
            let dbSizeInfo = await Db_size.query().where('db_id',id)
            res.render("db-size", {
                free: dbSizeInfo[0].db_free,
                used: dbSizeInfo[0].db_used
            });
            app.use('/db/' id , express.static("public"));

        } catch (error) {
            console.error(error)
        }

    });

    app.use('/db', router , express.static("public"));
    // app.use('/db/?', express.static("public"));

}

as you can see in the db.js i have redefine my public folder on the route, so like each time i create a route i have redefine my public folder on each route i make (otherwise it would look in the /theCalledRoute folder instead of /public for my static files), which was annoying but it worked. Now however that i added the /:id to it is looking db/:id folder to find all my static files instead of the public. I would have make a app.use('/everyidever', router , express.static("public")); for all the ids. Is there a better way to do this?. I need to export the necessary variables from my app.js for everything to work. Let me know if you need more info

CodePudding user response:

The definition of public dir for static assets at the beginning of the first file is correct

// app.use('/public', express.static(__dirname "/public"))

The URL for static files (styles, js, images, files, etc) should start with / in your templates, for instance, let's suppose that you have an image named logo.png in /public dir, so in your template you should refer to it as:

<img src="/logo.png"/>

Node JS will serve that image from your configured dir public, pay attention to / at the beggining of the path.

  • Related