Node.js Express (Web Framework)
Express.js is a popular Node.js web framework that provides robust routing, middleware, and template support. It is built on top of the Node.js core HTTP module and adds useful features for web development such as handling HTTP requests and routing.
In this tutorial, we'll cover the basics of how to use Node.js Express to quickly build a web application.
Syntax
The syntax for using Express.js to create a web server in Node.js is as follows:
const express = require('express')
const app = express()
// Define routes here
app.get('/', (req, res) => {
res.send('Hello World!')
})
// Start server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`)
})
Example
Here's a simple example of how to create an Express.js web application to serve a static file:
const express = require('express')
const app = express()
app.use(express.static('public'))
app.listen(3000, () => {
console.log('Server running on http://localhost:3000')
})
In this example, we're serving static files located in the "public" directory. When a file is requested, the contents of the file are returned in the HTTP response.
Output
When we run the example code above, the output will be:
Server running on http://localhost:3000
This means that our web application is up and running, and listening for HTTP requests on port 3000.
Explanation
In the example above, we first require the Express.js module and create an instance of the Express application using the express()
method.
We then use the express.static()
middleware to serve static files from the "public" directory. Any files requested will be looked up in the "public" directory, and the contents of the file will be returned in the HTTP response.
Finally, we start the server using the app.listen()
method, which tells the server to listen for HTTP requests on port 3000.
Use
Express.js can be used to quickly build web applications in Node.js. It provides robust routing and middleware support, making it easy to handle HTTP requests and respond with appropriate content.
Important Points
- Express.js provides an easy-to-use routing system that allows you to define routes for different HTTP methods and URLs.
- Express.js middleware can be used to perform pre-processing of incoming requests, or post-processing of outgoing responses.
- Express.js includes built-in support for handling JSON and URL-encoded form data.
Summary
In this tutorial, we discussed how to use the Node.js Express web framework to quickly build web applications. We covered the syntax, example, output, explanation, use, and important points of Express.js. With this knowledge, you can start building web applications with Node.js and Express.js.