உள்ளமைக்கப்பட்ட HTTP தொகுதி
Node.js ஒரு சக்திவாய்ந்த உள்ளமைக்கப்பட்ட HTTP தொகுதியை உள்ளடக்கியது, இது HTTP சேவையகங்களை உருவாக்கவும் HTTP கோரிக்கைகளை செய்யவும் உங்களை அனுமதிக்கிறது.
இந்த தொகுதி Node.js இல் வலை பயன்பாடுகள் மற்றும் APIகளை உருவாக்குவதற்கு அத்தியாவசியமானது.
HTTP சேவையகங்கள்
கோரிக்கைகளை கையாளவும் பதில்களை அனுப்பவும் HTTP சேவையகங்களை உருவாக்கவும்
HTTP கோரிக்கைகள்
மற்ற சேவையகங்களுக்கு HTTP கோரிக்கைகளை செய்யவும்
HTTP முறைகள்
வெவ்வேறு HTTP முறைகளை கையாளவும் (GET, POST, PUT, DELETE, முதலியன)
HTTP தொகுதியைச் சேர்த்தல்
HTTP தொகுதியைப் பயன்படுத்த, அதை உங்கள் பயன்பாட்டில் require() முறையைப் பயன்படுத்தி சேர்க்கவும்:
// Using CommonJS require (Node.js default)
const http = require('http');
// Or using ES modules (Node.js 14+ with "type": "module" in package.json)
// import http from 'http';
HTTP சேவையகத்தை உருவாக்குதல்
HTTP தொகுதியின் createServer() முறை ஒரு HTTP சேவையகத்தை உருவாக்குகிறது, இது குறிப்பிட்ட போர்ட்டில் கோரிக்கைகளைக் கேட்கிறது மற்றும் ஒவ்வொரு கோரிக்கைக்கும் ஒரு கால்பேக் செயல்பாட்டை இயக்குகிறது.
அடிப்படை HTTP சேவையக எடுத்துக்காட்டு
// Import the HTTP module
const http = require('http');
// Create a server object
const server = http.createServer((req, res) => {
// Set the response HTTP header with HTTP status and Content type
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send the response body as 'Hello, World!'
res.end('Hello, World!\n');
});
// Define the port to listen on
const PORT = 3000;
// Start the server and listen on the specified port
server.listen(PORT, 'localhost', () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
குறியீட்டைப் புரிந்துகொள்வது
சேவையகத்தை இயக்குதல்
சேவையகத்தை இயக்குவது எப்படி:
- குறியீட்டை server.js என்ற கோப்பில் சேமிக்கவும்
- Node.js ஐப் பயன்படுத்தி சேவையகத்தை இயக்கவும்:
node server.js - பதிலைப் பார்க்க உங்கள் உலாவியில் http://localhost:3000 க்குச் செல்லவும்
HTTP தலைப்புகளுடன் பணிபுரிதல்
HTTP தலைப்புகள் உங்கள் பதிலுடன் கூடுதல் தகவல்களை அனுப்ப உங்களை அனுமதிக்கின்றன.
நிலை குறியீடு மற்றும் பதில் தலைப்புகளை அமைக்க res.writeHead() முறை பயன்படுத்தப்படுகிறது.
பதில் தலைப்புகளை அமைத்தல்
const http = require('http');
const server = http.createServer((req, res) => {
// Set status code and multiple headers
res.writeHead(200, {
'Content-Type': 'text/html',
'X-Powered-By': 'Node.js',
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Set-Cookie': 'sessionid=abc123; HttpOnly'
});
res.end('Hello, World!
');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
பொதுவான HTTP நிலை குறியீடுகள்
| குறியீடு | செய்தி | விளக்கம் |
|---|---|---|
| 200 | OK | வெற்றிகரமான HTTP கோரிக்கைகளுக்கான நிலையான பதில் |
| 201 | Created | கோரிக்கை நிறைவேற்றப்பட்டு புதிய வளம் உருவாக்கப்பட்டது |
| 301 | Moved Permanently | வளம் ஒரு புதிய URL க்கு நகர்த்தப்பட்டது |
| 400 | Bad Request | கிளையன்ட் பிழையின் காரணமாக சேவையகம் கோரிக்கையை செயலாக்க முடியாது |
| 401 | Unauthorized | அங்கீகாரம் தேவைப்படுகிறது |
| 404 | Not Found | கோரிக்கையிடப்பட்ட வளத்தைக் கண்டறிய முடியவில்லை |
| 500 | Internal Server Error | எதிர்பாராத நிலை எதிர்கொள்ளப்பட்டது |
கோரிக்கை தலைப்புகளைப் படித்தல்
req.headers பொருளைப் பயன்படுத்தி கோரிக்கை தலைப்புகளை அணுகலாம்:
const http = require('http');
const server = http.createServer((req, res) => {
// Log all request headers
console.log('Request Headers:', req.headers);
// Get specific headers (case-insensitive)
const userAgent = req.headers['user-agent'];
const acceptLanguage = req.headers['accept-language'];
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`User-Agent: ${userAgent}\nAccept-Language: ${acceptLanguage}`);
});
server.listen(3000);
URLகள் மற்றும் வினா சரங்களுடன் பணிபுரிதல்
Node.js URLகள் மற்றும் வினா சரங்களுடன் பணிபுரிய உள்ளமைக்கப்பட்ட தொகுதிகளை வழங்குகிறது, இது URL இன் வெவ்வேறு பகுதிகளைக் கையாளவும் வினா அளவுருக்களைப் பாகுபடுத்தவும் எளிதாக்குகிறது.
கோரிக்கை URL ஐ அணுகுதல்
req.url பண்பு கோரிக்கையிடப்பட்ட URL சரத்தைக் கொண்டுள்ளது, எந்தவொரு வினா அளவுருக்களையும் உள்ளடக்கியது.
const http = require('http');
const server = http.createServer((req, res) => {
// Get the URL and HTTP method
const { url, method } = req;
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`You made a ${method} request to ${url}`);
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
URL தொகுதியுடன் URLகளைப் பாகுபடுத்துதல்
url தொகுதி URL தீர்மானம் மற்றும் பாகுபடுத்தலுக்கான பயன்பாடுகளை வழங்குகிறது.
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
// Parse the URL
const parsedUrl = url.parse(req.url, true);
// Get different parts of the URL
const pathname = parsedUrl.pathname; // The path without query string
const query = parsedUrl.query; // The query string as an object
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
pathname,
query,
fullUrl: req.url
}, null, 2));
});
server.listen(3000);
வினா சரங்களுடன் பணிபுரிதல்
மேம்பட்ட வினா சரம் கையாளுதலுக்கு, நீங்கள் querystring தொகுப்பைப் பயன்படுத்தலாம்:
const http = require('http');
const { URL } = require('url');
const querystring = require('querystring');
const server = http.createServer((req, res) => {
// Using the newer URL API (Node.js 10+)
const baseURL = 'http://' + req.headers.host + '/';
const parsedUrl = new URL(req.url, baseURL);
// Get query parameters
const params = Object.fromEntries(parsedUrl.searchParams);
// Example of building a query string
const queryObj = {
name: 'John Doe',
age: 30,
interests: ['programming', 'music']
};
const queryStr = querystring.stringify(queryObj);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
path: parsedUrl.pathname,
params,
exampleQueryString: queryStr
}, null, 2));
});
server.listen(3000);
வெவ்வேறு HTTP முறைகளைக் கையாளுதல்
RESTful APIகள் பொதுவாக வளங்களில் வெவ்வேறு செயல்பாடுகளைச் செய்ய வெவ்வேறு HTTP முறைகளைப் (GET, POST, PUT, DELETE, முதலியன) பயன்படுத்துகின்றன.
Node.js HTTP சேவையகத்தில் வெவ்வேறு HTTP முறைகளைக் கையாளுவது எப்படி என்பது இங்கே:
const http = require('http');
const { URL } = require('url');
// In-memory data store (for demonstration)
let todos = [
{ id: 1, task: 'Learn Node.js', completed: false },
{ id: 2, task: 'Build an API', completed: false }
];
const server = http.createServer((req, res) => {
const { method, url } = req;
const parsedUrl = new URL(url, `http://${req.headers.host}`);
const pathname = parsedUrl.pathname;
// Set CORS headers (for development)
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
// Handle preflight requests
if (method === 'OPTIONS') {
res.writeHead(204);
res.end();
return;
}
// Route: GET /todos
if (method === 'GET' && pathname === '/todos') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(todos));
}
// Route: POST /todos
else if (method === 'POST' && pathname === '/todos') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const newTodo = JSON.parse(body);
newTodo.id = todos.length > 0 ? Math.max(...todos.map(t => t.id)) + 1 : 1;
todos.push(newTodo);
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(newTodo));
} catch (error) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
}
// Route: PUT /todos/:id
else if (method === 'PUT' && pathname.startsWith('/todos/')) {
const id = parseInt(pathname.split('/')[2]);
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const updatedTodo = JSON.parse(body);
const index = todos.findIndex(t => t.id === id);
if (index === -1) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Todo not found' }));
} else {
todos[index] = { ...todos[index], ...updatedTodo };
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(todos[index]));
}
} catch (error) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
}
// Route: DELETE /todos/:id
else if (method === 'DELETE' && pathname.startsWith('/todos/')) {
const id = parseInt(pathname.split('/')[2]);
const index = todos.findIndex(t => t.id === id);
if (index === -1) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Todo not found' }));
} else {
todos = todos.filter(t => t.id !== id);
res.writeHead(204);
res.end();
}
}
// 404 Not Found
else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not Found' }));
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
HTTP முறைகளுக்கான சிறந்த நடைமுறைகள்:
- GET: ஒரு வளம் அல்லது வளங்களின் தொகுப்பைப் பெறவும் (idempotent ஆக இருக்க வேண்டும்)
- POST: ஒரு புதிய வளத்தை உருவாக்கவும் (idempotent அல்ல)
- PUT: ஏற்கனவே உள்ள வளத்தைப் புதுப்பிக்கவும் அல்லது இல்லையென்றால் உருவாக்கவும் (idempotent)
- PATCH: ஒரு வளத்தை பகுதியாகப் புதுப்பிக்கவும்
- DELETE: ஒரு வளத்தை அகற்றவும் (idempotent)
- HEAD: பதில் உடல் இல்லாமல் GET போன்றது
- OPTIONS: இலக்கு வளத்திற்கான தகவல்தொடர்பு விருப்பங்களை விவரிக்கவும்
ஸ்ட்ரீமிங் பதில்கள்
Node.js ஸ்ட்ரீம்கள் பெரிய அளவிலான தரவை திறம்பட கையாள சக்திவாய்ந்தவை. HTTP தொகுதி கோரிக்கை உடல்களைப் படிப்பதற்கும் பதில்களை எழுதுவதற்கும் ஸ்ட்ரீம்களுடன் நன்றாக வேலை செய்கிறது.
ஒரு பெரிய கோப்பை ஸ்ட்ரீம் செய்தல்
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
// Get the file path from the URL
const filePath = path.join(__dirname, req.url);
// Check if file exists
fs.access(filePath, fs.constants.F_OK, (err) => {
if (err) {
res.statusCode = 404;
res.end('File not found');
return;
}
// Get file stats
fs.stat(filePath, (err, stats) => {
if (err) {
res.statusCode = 500;
res.end('Server error');
return;
}
// Set appropriate headers
res.setHeader('Content-Length', stats.size);
res.setHeader('Content-Type', 'application/octet-stream');
// Create read stream and pipe to response
const stream = fs.createReadStream(filePath);
// Handle errors
stream.on('error', (err) => {
console.error('Error reading file:', err);
if (!res.headersSent) {
res.statusCode = 500;
res.end('Error reading file');
}
});
// Pipe the file to the response
stream.pipe(res);
});
});
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`File server running at http://localhost:${PORT}/`);
});