Sunday, 14 June 2020

Static Files in /controllers

Hey r/node,I built a pretty simple static file server with this folder structure:.├── public/├── routes/│ └── index.js├── controllers/│ └── index.js├── app.js├── package.json└── .gitignoreAnd here's the code for app.js:​```const express = require('express');const app = express();const morgan = require('morgan');const path = require('path');app.use(express.static('public'));app.use(morgan('dev'));const home = require('./routes/index.js');const about = require('./routes/about.js');app.use('/', home);app.use('/about', about);/* HANDLING ERRORS */app.use((req, res) => {res.status(404);res.sendFile(path.join(__dirname + '/views/404.html'));});app.listen(5000);console.log("Server running at http://localhost:5000");```​routes/index.js:```const express = require('express');const router = express.Router();const home = require('../controllers/index.js');router.get('/', home.homePage);module.exports = router```And controllers/index.js```exports.homePage = (req, res) => {res.sendFile('/index.html');}```If I want to make the controller file for the about page, where I will serve an HTML file, how do I do it? Because I can't serve the file if it is in the public folder while I'm in the controller one... Is there a way to do it? But why does it work for the index file? It is better to make another file in the routes folder called about.js? Hope you understood my question, have a nice day and thank you!

Submitted June 14, 2020 at 04:05PM by _folgo_

No comments:

Post a Comment