expressjsHow do I create an Express.js boilerplate?
- To create an Express.js boilerplate, first install Express.js using the command
npm install express. - Create a file named
server.jsand add the following code to it:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
This will create an Express.js server that listens on port 5000 and responds to requests with "Hello World!"
- To add additional routes, add a
GETorPOSTrequest to theappobject, like this:
app.get('/about', (req, res) => {
res.send('About page');
});
This adds a route to the /about page.
- To add middleware to the application, use
app.use()like this:
app.use(express.json());
This adds the express.json() middleware to the application.
- To add a template engine, install the desired template engine and then configure Express.js to use it. For example, to use Pug, install it using
npm install pugand then add the following code toserver.js:
app.set('view engine', 'pug');
- To serve static files, use
app.use()like this:
app.use(express.static('public'));
This will serve all files in the public directory.
- To add a database, install the desired database driver and then configure Express.js to use it. For example, to use Mongoose, install it using
npm install mongooseand then add the following code toserver.js:
const mongoose = require('mongoose');
mongoose
.connect('mongodb://localhost/my_database', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to MongoDB...', err));
This will connect to a MongoDB database running on the local machine.
At this point, the Express.js boilerplate is complete.
Relevant Links
More of Expressjs
- How do I use adm-zip with Express.js?
- How can I use Express.js to generate a zip response?
- How can I use express-zip js to zip and download files?
- How do I use Yarn to add Express.js to my project?
- How do I set the time zone in Express.js?
- How do I set up a YAML configuration file for a Node.js Express application?
- How do I use Express.js to parse YAML files?
- How can I use Express.js and Winston together to create a logging system?
- How do I find Express.js tutorials on YouTube?
See more codes...