How to Handle GET Request in Express API: Simple Guide
To handle a GET request in an Express API, use
app.get(path, callback) where path is the URL and callback is a function that sends a response. This function receives req and res objects to access request data and send back the response.Why This Happens
Sometimes, developers forget to use the correct method or callback signature to handle GET requests in Express. This causes the server to not respond or throw errors because Express doesn't know how to handle the request.
javascript
const express = require('express'); const app = express(); // Incorrect: Using app.post instead of app.get for GET requests app.post('/hello', (req, res) => { res.send('Hello World'); }); app.listen(3000, () => console.log('Server running on port 3000'));
Output
GET /hello returns 404 Not Found because app.post does not handle GET requests.
The Fix
Change the method to app.get to correctly handle GET requests. The callback function should accept req and res parameters and use res.send() or similar to send a response.
javascript
const express = require('express'); const app = express(); // Correct: Using app.get to handle GET requests app.get('/hello', (req, res) => { res.send('Hello World'); }); app.listen(3000, () => console.log('Server running on port 3000'));
Output
When you visit http://localhost:3000/hello, the server responds with 'Hello World'.
Prevention
Always match the HTTP method (GET, POST, etc.) with the correct Express method (app.get, app.post). Use consistent callback signatures with req and res. Enable linting tools like ESLint to catch common mistakes early. Test your routes with tools like Postman or your browser to confirm they respond as expected.
Related Errors
Common related errors include:
- 404 Not Found: Happens if the route path or method is incorrect.
- Cannot set headers after they are sent: Occurs if you try to send multiple responses in one callback.
- Callback not called: If you forget to send a response, the request will hang.
Key Takeaways
Use app.get(path, callback) to handle GET requests in Express.
The callback must accept req and res and send a response with res.send or similar.
Match HTTP methods with the correct Express method to avoid 404 errors.
Test your API routes regularly to ensure they respond correctly.
Use linting and testing tools to catch mistakes early.