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 Express.js to parse YAML files?
- How can I set up X-Frame-Options in ExpressJS?
- How do I set the keepalivetimeout in Express.js?
- How do I use Express.js to process form data?
- How can I parse XML data using Express.js?
- How can I use Express.js to generate a zip response?
- How do Express.js and Node.js differ in terms of usage?
- How can I use express-zip js to zip and download files?
- How can I render HTML pages using Express.js?
- How can I use Express.js and Babel together to develop a web application?
See more codes...