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.js
and 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
GET
orPOST
request to theapp
object, 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 pug
and 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 mongoose
and 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 implement CSRF protection in an Express.js application?
- How can I use express-zip js to zip and download files?
- How can I set up X-Frame-Options in ExpressJS?
- How do I find Express.js tutorials on YouTube?
- How do I download a zip file using Express.js?
- 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 can I disable the X-Powered-By header in Express.js?
- How can I use the x-forwarded-for header in Express.js?
- How do I use adm-zip with Express.js?
See more codes...