Web II Handling Requests and Responses Lesson005
Web II Handling Requests and Responses Lesson005
Handling HTTP requests and responses involves a client (like a web browser)
sending a request to a server, which then processes the request and sends back a
response.
The client and server exchange data through HTTP messages, which can be in the
form of text or binary.
Here's a breakdown of the process:
1. Client Sends a Request:
The client initiates the connection to the server.
It sends an HTTP request, which includes information like the requested
URL, HTTP method (GET, POST, etc.), and any headers or data.
2. Server Processes the Request:
The server receives the request.
It processes the request based on the URL, HTTP method, and any other
parameters.
It might query a database, perform calculations, or access other resources to
generate a response.
3. Server Sends a Response:
The server creates an HTTP response.
The response includes a status code (e.g., 200 OK, 404 Not Found), headers,
and the data that the client requested.
The server sends the response back to the client.
4. Client Receives and Processes the Response:
The client receives the response from the server.
It parses the response, extracting information like the status code, headers,
and data.
It uses the received information to update the user interface or perform other
actions.
Example Scenario:
Imagine you type a website address into your browser (the client).
1. Client: The browser sends an HTTP GET request to the server, requesting
the web page.
2. Server: The web server receives the request and finds the corresponding
web page.
3. Server: The server sends an HTTP response containing the web page data
and a status code (e.g., 200 OK).
4. Client: The browser receives the response and displays the web page.
Key Concepts:
HTTP Methods:
Common methods include GET (retrieve data), POST (create data), PUT
(replace data), PATCH (update data), and DELETE (delete data).
Status Codes:
Indicate the success or failure of the request (e.g., 200 OK, 404 Not Found, 500
Internal Server Error).
Headers:
Provide additional information about the request or response, such as content
type, cookies, and authentication details.
EXAMPLE
Server.js
const express = require('express');
const app = express();
const userRoutes = require('./routes/users');
app.use(express.json());
// Use routes
app.use('/api/users', userRoutes);
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Route/user.js
const express = require('express');
const router = express.Router();
const usersController = require('../controllers/users');
router.get('/', usersController.getUsers);
router.post('/', usersController.createUser);
router.get('/:id', usersController.getUserById);
module.exports = router;
controllers/user.js
let users = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' }
];
// GET /api/users
const getUsers = (req, res) => {
res.json(users);
};
// POST /api/users
const createUser = (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({
error: 'Both name and email are required'
});
}
// GET /api/users/:id
const getUserById = (req, res) => {
const id = parseInt(req.params.id);
const user = users.find(u => u.id === id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
};
module.exports = {
getUsers,
createUser,
getUserById
};
Testing in Postman
A. GET All Users (GET /api/users)
1. Open Postman and create a new request.
2. Set Request Type: GET
3. Enter URL: http://localhost:3000/api/users
4. Click "Send"
5. Expected Response:
[
{ "id": 1, "name": "John Doe", "email": "john@example.com" },
{ "id": 2, "name": "Jane Smith", "email": "jane@example.com" }
]
Expected
Endpoint Method URL Body (JSON)
Response
/api/
Get user by ID GET - Single user
users/1
{ "name":
Create user 400, error
POST /api/users "..." } (missing
(error) message
email)
QUERY PARAMETERS
A query parameter in Express.js is a way to pass data to the server through the
URL.
These parameters are appended to the end of the URL after a question mark ? and
are represented as key-value pairs, separated by ampersands &.
Express.js provides the req.query object to access these parameters within route
handlers.
For example, consider the following URL:
/search?q=javascript&page=2
In this URL, q and page are query parameters with
values javascript and 2 respectively.
To access these parameters in an Express.js route handler, you can use req.query:
app.get('/search', (req, res) => {
const searchTerm = req.query.q;
const page = req.query.page;
Controllers/users.js
// Define users array OUTSIDE the functions (shared across all routes)
let users = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' }
];
// GET /api/users
const getUsers = (req, res) => {
// Access query parameters
const { name, email,} = req.query;
res.json(filteredUsers);
};
// POST /api/users
const createUser = (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({
error: 'Both name and email are required'
});
}
// GET /api/users/:id
const getUserById = (req, res) => {
const id = parseInt(req.params.id);
const user = users.find(u => u.id === id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
};
module.exports = {
getUsers,
createUser,
getUserById
};
Server.js
const express = require('express');
const app = express();
// Import routes
const userRoutes = require('./routes/users');
// Use routes
app.use('/api/users', userRoutes);
Router/user.js
const express = require('express');
const router = express.Router();
const usersController = require('../controllers/users');
// GET /api/users
router.get('/', usersController.getUsers);
// POST /api/users
router.post('/', usersController.createUser);
// GET /api/users/:id
router.get('/:id', usersController.getUserById);
module.exports = router;