http methods and status code in Node JS
In Node.js, understanding HTTP methods and status codes is crucial for handling HTTP requests and responses effectively. These concepts are fundamental for web development and API design. Here's a detailed explanation:
HTTP Methods
HTTP methods define the actions that can be performed on resources (e.g., data) on a web server. Each method has a specific purpose and semantics. The http
module in Node.js supports these methods when creating servers or making requests.
1. GET
Purpose: Retrieve data from a server.
Usage: Used to request data from a specific resource.
Example: Fetching a user profile from an API.
// Making a GET request with http const options = { hostname: 'api.example.com', port: 80, path: '/users/123', method: 'GET', }; const req = http.request(options, (res) => { // Handle response }); req.end();
2. POST
Purpose: Send data to a server to create or update a resource.
Usage: Used for submitting form data, creating new resources, or making modifications.
Example: Submitting a new user registration form.
// Making a POST request with http const postData = JSON.stringify({ name: 'John Doe', email: 'john@example.com' }); const options = { hostname: 'api.example.com', port: 80, path: '/users', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': postData.length, }, }; const req = http.request(options, (res) => { // Handle response }); req.write(postData); req.end();
3. PUT
Purpose: Update a resource on the server.
Usage: Used to send data to update an existing resource.
Example: Updating user information.
// Making a PUT request with http const putData = JSON.stringify({ email: 'new-email@example.com' }); const options = { hostname: 'api.example.com', port: 80, path: '/users/123', method: 'PUT', headers: { 'Content-Type': 'application/json', 'Content-Length': putData.length, }, }; const req = http.request(options, (res) => { // Handle response }); req.write(putData); req.end();
4. DELETE
Purpose: Remove a resource from the server.
Usage: Used to delete a specific resource.
Example: Removing a user profile.
// Making a DELETE request with http const options = { hostname: 'api.example.com', port: 80, path: '/users/123', method: 'DELETE', }; const req = http.request(options, (res) => { // Handle response }); req.end();
5. HEAD
Purpose: Retrieve headers of a resource without the body.
Usage: Used to check metadata or existence of a resource.
Example: Checking if a resource exists.
// Making a HEAD request with http const options = { hostname: 'api.example.com', port: 80, path: '/users/123', method: 'HEAD', }; const req = http.request(options, (res) => { // Handle response headers }); req.end();
6. OPTIONS
Purpose: Describe the communication options for the target resource.
Usage: Used to retrieve allowed HTTP methods and other options supported by the server.
Example: Checking allowed methods for a resource.
// Making an OPTIONS request with http const options = { hostname: 'api.example.com', port: 80, path: '/users/123', method: 'OPTIONS', }; const req = http.request(options, (res) => { // Handle response headers }); req.end();
HTTP Status Codes
HTTP status codes are issued by the server to indicate the result of the request. They provide information about the success or failure of the request. They are categorized into several classes.
1. Informational (1xx)
- 100 Continue: Indicates that the initial part of the request has been received and the client should continue.
- 101 Switching Protocols: Indicates the server is switching protocols as requested by the client.
2. Success (2xx)
- 200 OK: The request was successful, and the server responded with the requested data.
- 201 Created: The request was successful, and a new resource was created.
- 204 No Content: The request was successful, but there is no content to send in the response.
3. Redirection (3xx)
- 301 Moved Permanently: The resource has been permanently moved to a new URL.
- 302 Found: The resource is temporarily located at a different URL.
- 304 Not Modified: The resource has not been modified since the last request.
4. Client Error (4xx)
- 400 Bad Request: The server could not understand the request due to invalid syntax.
- 401 Unauthorized: Authentication is required or has failed.
- 403 Forbidden: The server understands the request but refuses to authorize it.
- 404 Not Found: The requested resource could not be found.
- 409 Conflict: The request could not be completed due to a conflict with the current state of the resource.
5. Server Error (5xx)
- 500 Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request.
- 501 Not Implemented: The server does not support the functionality required to fulfill the request.
- 502 Bad Gateway: The server received an invalid response from an upstream server.
- 503 Service Unavailable: The server is currently unable to handle the request due to temporary overloading or maintenance.
Using HTTP Methods and Status Codes in Node.js
When creating an HTTP server with Node.js, you can use these methods and status codes to handle different types of requests and responses appropriately.
Example: Handling HTTP Methods and Status Codes
const http = require('http');
const server = http.createServer((req, res) => {
switch (req.method) {
case 'GET':
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'GET request received' }));
break;
case 'POST':
res.statusCode = 201;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'POST request received' }));
break;
case 'DELETE':
res.statusCode = 204;
res.end();
break;
default:
res.statusCode = 405; // Method Not Allowed
res.end('Method Not Allowed');
break;
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Summary
- HTTP Methods: Define the actions for interacting with resources (e.g., GET, POST, PUT, DELETE).
- HTTP Status Codes: Provide feedback about the request’s outcome (e.g., 200 OK, 404 Not Found, 500 Internal Server Error).
- Node.js Integration: The
http
module allows you to handle these methods and status codes when creating servers or making requests.