expressjsHow do I create a route in Express.js?
Creating routes in Express.js is a simple process. Here is an example of creating a route:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
Output example
Server started on port 3000
The code consists of four parts:
- Require the Express.js module:
const express = require('express')
- Create an Express.js application instance:
const app = express()
- Create a route handler for the route path:
app.get('/', (req, res) => { ... })
- Start the server:
app.listen(3000, () => { ... })
The first two parts of the code are necessary for all Express.js applications. The third part is where the route is created. The route path is provided as the first argument and the route handler is provided as the second argument. The route handler is a function that is called when the route is requested. In this example, the route handler sends a response with the text Hello World!
. The fourth part of the code starts the server on port 3000.
For more information about creating routes in Express.js, see the documentation.
More of Expressjs
- How do I download a zip file using Express.js?
- How do I find Express.js tutorials on YouTube?
- How do I implement CSRF protection in an Express.js application?
- How can I use Express.js to make an XHR request?
- How can I set up X-Frame-Options in ExpressJS?
- How do I use adm-zip with Express.js?
- How can I use express-zip js to zip and download files?
- How can I use the x-forwarded-for header in Express.js?
- How do I set up a YAML configuration file for a Node.js Express application?
- How can I use Express.js to develop a web application?
See more codes...