0
0
ExpressHow-ToBeginner · 3 min read

How to Use app.get in Express: Simple Guide with Examples

In Express, use app.get(path, callback) to handle HTTP GET requests to a specific path. The callback function runs when the path is requested, letting you send a response back to the client.
📐

Syntax

The app.get method takes two main parts:

  • path: A string or pattern that matches the URL path to listen for.
  • callback: A function with request and response parameters that runs when the path is requested.

This callback handles the request and sends a response.

javascript
app.get(path, (req, res) => {
  // handle request
  res.send('response');
})
💻

Example

This example creates a simple Express server that responds with 'Hello World!' when the root URL is accessed with a GET request.

javascript
import express from 'express';

const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
Output
Server running at http://localhost:3000
⚠️

Common Pitfalls

Some common mistakes when using app.get include:

  • Forgetting to call res.send() or res.end(), which leaves the request hanging.
  • Using the wrong HTTP method like app.post when expecting GET requests.
  • Not specifying the correct path, causing the route to never match.
  • Placing middleware or routes in the wrong order, which can block the app.get handler.
javascript
/* Wrong: Missing response send */
app.get('/test', (req, res) => {
  // no res.send or res.end here
});

/* Right: Always send a response */
app.get('/test', (req, res) => {
  res.send('Test route');
});
📊

Quick Reference

PartDescription
app.get(path, callback)Defines a route for GET requests at the given path
pathURL path string or pattern to match requests
callback(req, res)Function to handle the request and send a response
res.send(data)Sends a response back to the client
res.json(object)Sends a JSON response

Key Takeaways

Use app.get(path, callback) to handle HTTP GET requests in Express.
Always send a response inside the callback using res.send or res.json.
Ensure the path matches the URL you want to handle exactly.
Order your routes and middleware carefully to avoid blocking handlers.
app.get only handles GET requests; use other methods for POST, PUT, etc.