What is app.get()?
app.get()
is a specific method in Express.js used to define route handlers for GET requests. It is one of the HTTP method-specific functions provided by Express.js for routing, along with app.post()
, app.put()
, app.delete()
, etc.
Key Features of app.get()
- Route Handling:
app.get()
is used to define a route handler for GET requests made to a specific path. - Path-Specific: It requires a URL path as an argument and executes the handler function only when a GET request matches the specified path.
- HTTP Method Specific: It handles only GET requests, ignoring requests of other types (POST, PUT, DELETE, etc.).
- Response Sending: It typically ends the request-response cycle by sending a response back to the client.
Example: Implementation to show the use of above given method.
// Requiring module
const express = require('express');
const app = express();
app.get('/', function (req, res) {
res.send('Hello Geek');
})
// Server setup
const server = app.listen(8080, function () {
const host = server.address().address
const port = server.address().port
console.log(" Listening : ", port)
})
Run the index.js file using the following command:
node index.js
Output:
Difference between app.use() and app.get() in Express.js
Express.js, a popular web application framework for Node.js, provides a powerful set of methods for routing HTTP requests. Among these methods, app.use()
and app.get()
are two fundamental functions that serve different purposes. Understanding their differences is essential for building efficient and well-structured Express applications.
Contact Us