Express Project Structure
Structure
- app.js: main file, houses the embedded server and application logic
- /public: contains static files to be served by the embedded server
- /routes: houses custom routing for the REST API servers (not needed for a web app)
- /routes/users.js: endpoint/routes for resources such as users
- /views: contains templates that can be processed by a template engine (not needed for REST APIs)
- /package.json: project manifest
- /www: boot up script folder
Note: a web app is a traditional web application (thick server) with 100% server-side rendering while a REST API is a data only server (rendering happens and UI is hosted on the clients)
Typical Express App Structure
The main Express app (server) file is typically named app.js, server.js or index.js. It has the following sections in the order from top of the file to the bottom of the file:- Imports
- Instantiations
- Configurations
- Middleware
- Routes
- Error handlers
- Server bootup or server export
If we go back to our hello world example, we can see some of the sections but not all of them:
// Imports
const express = require('express')
// Instantiations
const app = express()
// Routes
app.get('/', (req, res)=>{
res.send('hello world')
})
// Bootup
app.listen(3000)
Configuring Express
The Express server could be configured before it starts (none of the configurations are mandatory). Developers define (set) configuration via the set method where the first argument is the name and the second is the value:
The Express server could be configured before it starts (none of the configurations are mandatory). Developers define (set) configuration via the set method where the first argument is the name and the second is the value:
const express = require('express')
const app = express()
app.set('port', process.env.PORT || 3000)
app.set('views', 'templates') // The directory the templates are stored in
app.set('view engine', 'jade')
In the code above, views sets the template directory (folder with server-side templates) to templates instead of the default value of views. The line after that with view engine, sets the template engine to jade.
Ref:
No comments:
Post a Comment