HTTP கோரிக்கை பொருள்
HTTP கோரிக்கை பொருள் உள்நாட்டில் Node.js மூலம் உருவாக்கப்பட்டு HTTP கோரிக்கைகளைச் செய்யும் போது கோரிக்கை நிகழ்வு callback க்கு முதல் அளவுருவாக அனுப்பப்படுகிறது. HTTP சேவையகங்களுடன் பயன்படுத்தப்படும் போது client இலிருந்து வரும் செய்தியை அல்லது HTTP clients உடன் பயன்படுத்தப்படும் போது வெளிச்செல்லும் செய்தியை இது குறிக்கிறது.
Node.js இல் இரண்டு முக்கிய வகையான கோரிக்கை பொருள்கள் உள்ளன:
http.ClientRequest
வெளிப்புற HTTP கோரிக்கைகளைச் செய்யும் போது உருவாக்கப்பட்டது
http.IncomingMessage
client கோரிக்கைகளைக் கையாளும் போது சேவையகத்தால் பெறப்பட்டது
ClientRequest பொருள்
http.ClientRequest பொருள் http.request() அல்லது http.get() அழைக்கப்படும் போது உருவாக்கப்பட்ட Writable Stream இன் ஒரு instance ஆகும். இது நீங்கள் ஒரு சேவையகத்திற்கு அனுப்பும் வெளிப்புற HTTP கோரிக்கையைக் குறிக்கிறது.
ClientRequest உருவாக்குதல்
const http = require('http');
// ஒரு client கோரிக்கையை உருவாக்கு
const req = http.request({
hostname: 'example.com',
port: 80,
path: '/',
method: 'GET'
}, (res) => {
// பதிலைக் கையாள (IncomingMessage)
console.log(`Status: ${res.statusCode}`);
});
// கோரிக்கையை முடி
req.end();
ClientRequest பண்புகள்
| பண்பு | விளக்கம் |
|---|---|
| request.aborted | கோரிக்கை கைவிடப்பட்டதா என்பதைக் குறிக்கும் boolean |
| request.connection | அடிப்படை socket க்கான குறிப்பு |
| request.socket | அடிப்படை socket க்கான குறிப்பு. request.connection இன் alias |
| request.finished | கோரிக்கை தரவை அனுப்புவது முடிந்ததா என்பதைக் குறிக்கும் boolean |
| request.path | கோரிக்கை பாதை |
| request.method | கோரிக்கை முறை (GET, POST, முதலியன) |
| request.host | கோரிக்கை host |
ClientRequest முறைகள்
| முறை | விளக்கம் |
|---|---|
| request.abort() | கோரிக்கையை கைவிடப்பட்டதாகக் குறிக்கிறது |
| request.destroy([error]) | கோரிக்கையை அழிக்கிறது. விருப்பமாக அனுப்பப்பட்ட பிழையை வெளியிடுகிறது |
| request.end([data[, encoding]][, callback]) | கோரிக்கையை அனுப்புவதை முடிக்கிறது. உடலின் எந்தப் பகுதிகளும் அனுப்பப்படவில்லை என்றால், அவற்றை ஸ்ட்ரீமுக்கு flush செய்யும் |
| request.flushHeaders() | கோரிக்கை தலைப்புகளை flush செய்கிறது |
| request.getHeader(name) | வரிசையில் உள்ள ஆனால் இன்னும் அனுப்பப்படாத தலைப்பின் மதிப்பைப் பெறுகிறது |
| request.removeHeader(name) | அனுப்புவதற்கு வரிசையில் உள்ள தலைப்பை அகற்றுகிறது |
| request.setHeader(name, value) | தலைப்புகள் பொருளுக்கு ஒரு தனி தலைப்பு மதிப்பை அமைக்கிறது |
| request.setNoDelay([noDelay]) | socket இன் noDelay விருப்பத்தை அமைக்கிறது |
| request.setSocketKeepAlive([enable][, initialDelay]) | socket இன் keepAlive விருப்பத்தை அமைக்கிறது |
| request.setTimeout(timeout[, callback]) | கோரிக்கைக்கான timeout மதிப்பை அமைக்கிறது |
| request.write(chunk[, encoding][, callback]) | உடலின் ஒரு chunk ஐ அனுப்புகிறது |
ClientRequest நிகழ்வுகள்
| நிகழ்வு | விளக்கம் |
|---|---|
| 'abort' | கோரிக்கை கைவிடப்படும் போது வெளியிடப்படுகிறது |
| 'connect' | ஒரு சேவையகம் CONNECT முறையுடன் ஒரு கோரிக்கைக்குப் பதிலளிக்கும் போது வெளியிடப்படுகிறது |
| 'continue' | சேவையகம் '100 Continue' HTTP பதிலை அனுப்பும் போது வெளியிடப்படுகிறது |
| 'information' | சேவையகம் 1xx பதிலை அனுப்பும் போது வெளியிடப்படுகிறது (101 Upgrade தவிர) |
| 'response' | இந்தக் கோரிக்கைக்கு ஒரு பதில் பெறப்படும் போது வெளியிடப்படுகிறது. இந்த நிகழ்வு ஒருமுறை மட்டுமே வெளியிடப்படும் |
| 'socket' | இந்தக் கோரிக்கைக்கு ஒரு socket ஒதுக்கப்படும் போது வெளியிடப்படுகிறது |
| 'timeout' | கோரிக்கை timeout ஆகும் போது வெளியிடப்படுகிறது |
| 'upgrade' | சேவையகம் upgrade உடன் பதிலளிக்கும் போது வெளியிடப்படுகிறது |
| 'close' | கோரிக்கை மூடப்படும் போது வெளியிடப்படுகிறது |
| 'error' | பிழை ஏற்படும் போது வெளியிடப்படுகிறது |
IncomingMessage பொருள்
http.IncomingMessage பொருள் ஒரு HTTP சேவையகத்தால் உருவாக்கப்பட்டு 'request' நிகழ்வுக்கு முதல் வாதமாக அனுப்பப்படுகிறது. இது ஒரு உள்வரும் செய்தியைக் குறிக்கிறது, பொதுவாக client இலிருந்து ஒரு கோரிக்கை அல்லது சேவையகத்திலிருந்து ஒரு பதில்.
சேவையகத்தில் IncomingMessage ஐ அணுகுதல்
const http = require('http');
// HTTP சேவையகத்தை உருவாக்கு
const server = http.createServer((req, res) => {
// 'req' ஒரு IncomingMessage பொருள்
console.log(`Received ${req.method} request for ${req.url}`);
res.end('Hello World');
});
server.listen(8080);
IncomingMessage பண்புகள்
| பண்பு | விளக்கம் |
|---|---|
| message.headers | கோரிக்கை/பதில் தலைப்புகள் பொருள் |
| message.httpVersion | client அனுப்பிய HTTP பதிப்பு (எ.க., '1.1', '1.0') |
| message.method | கோரிக்கை முறை ஒரு சரமாக (கோரிக்கை பொருள்களுக்கு மட்டும்) |
| message.rawHeaders | அவை பெறப்பட்டதைப் போலவே raw கோரிக்கை/பதில் தலைப்புகள் பட்டியல் |
| message.rawTrailers | அவை பெறப்பட்டதைப் போலவே raw கோரிக்கை/பதில் trailer keys மற்றும் values |
| message.socket | இணைப்புடன் தொடர்புடைய net.Socket பொருள் |
| message.statusCode | HTTP பதில் நிலை குறியீடு (பதில் பொருள்களுக்கு மட்டும்) |
| message.statusMessage | HTTP பதில் நிலை செய்தி (பதில் பொருள்களுக்கு மட்டும்) |
| message.trailers | கோரிக்கை/பதில் trailer தலைப்புகள் பொருள் |
| message.url | கோரிக்கை URL சரம் (கோரிக்கை பொருள்களுக்கு மட்டும்) |
IncomingMessage முறைகள்
| முறை | விளக்கம் |
|---|---|
| message.destroy([error]) | செய்தியை அழிக்கிறது. விருப்பமாக அனுப்பப்பட்ட பிழையை வெளியிடுகிறது |
| message.setTimeout(msecs, callback) | socket இன் timeout மதிப்பை அமைக்கிறது |
அடிப்படை GET கோரிக்கை எடுத்துக்காட்டு
GET கோரிக்கையைச் செய்ய http.get() ஐப் பயன்படுத்தும் ஒரு அடிப்படை எடுத்துக்காட்டு:
const http = require('http');
// ஒரு எளிய GET கோரிக்கையைச் செய்யவும்
http.get('http://example.com', (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
console.log(`Status Code: ${statusCode}`);
console.log(`Content-Type: ${contentType}`);
let error;
if (statusCode !== 200) {
error = new Error(`Request Failed. Status Code: ${statusCode}`);
} else if (!/^text\/html/.test(contentType)) {
error = new Error(`Invalid content-type. Expected text/html but received ${contentType}`);
}
if (error) {
console.error(error.message);
// நினைவகத்தை விடுவிக்க பதில் தரவை உட்கொள்ளவும்
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
// வரும் போது பதில் தரவைச் சேகரிக்கவும்
res.on('data', (chunk) => { rawData += chunk; });
// முழுமையான பதிலைச் செயலாக்கவும்
res.on('end', () => {
try {
console.log(`Response length: ${rawData.length} characters`);
console.log('First 100 characters:');
console.log(rawData.substring(0, 100) + '...');
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
POST கோரிக்கை எடுத்துக்காட்டு
தரவுடன் POST கோரிக்கையைச் செய்தல்:
const http = require('http');
// POST கோரிக்கையில் அனுப்ப வேண்டிய தரவு
const postData = JSON.stringify({
'name': 'John Doe',
'email': 'john@example.com',
'message': 'Hello from Node.js HTTP client!'
});
// கோரிக்கை விருப்பங்கள்
const options = {
hostname: 'postman-echo.com',
port: 80,
path: '/post',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
// கோரிக்கையை உருவாக்கு
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
let responseData = '';
res.on('data', (chunk) => {
responseData += chunk;
});
res.on('end', () => {
console.log('Response body:');
try {
// JSON ஆக parse செய்ய முயற்சி
const parsedData = JSON.parse(responseData);
console.log(JSON.stringify(parsedData, null, 2));
} catch (e) {
// JSON இல்லையென்றால், உரையாகக் காட்டு
console.log(responseData);
}
});
});
req.on('error', (e) => {
console.error(`Problem with request: ${e.message}`);
});
// கோரிக்கை உடலுக்கு தரவை எழுது
req.write(postData);
// கோரிக்கையை முடி
req.end();
கோரிக்கை தலைப்புகளைக் கையாளுதல்
கோரிக்கை தலைப்புகளுடன் பணிபுரிதல்:
const http = require('http');
// கோரிக்கை தலைப்புகளை நிரூபிக்க ஒரு சேவையகத்தை உருவாக்கு
const server = http.createServer((req, res) => {
// கோரிக்கை தகவலைக் காட்டு
console.log(`Request received: ${req.method} ${req.url}`);
console.log(`HTTP Version: ${req.httpVersion}`);
// நிலையான தலைப்புகளைக் காட்டு
console.log('\nStandard Headers:');
const stdHeaders = ['host', 'user-agent', 'accept', 'accept-language', 'content-type', 'content-length'];
stdHeaders.forEach(header => {
if (req.headers[header]) {
console.log(`${header}: ${req.headers[header]}`);
}
});
// raw தலைப்புகளைக் காட்டு (name-value ஜோடிகள்)
console.log('\nRaw Headers:');
for (let i = 0; i < req.rawHeaders.length; i += 2) {
console.log(`${req.rawHeaders[i]}: ${req.rawHeaders[i+1]}`);
}
// பதிலை உருவாக்கு
res.writeHead(200, {'Content-Type': 'text/html'});
// தலைப்புகள் தகவலுடன் பதிலை அனுப்பு
res.end(`
Request Headers
Your Request Headers
${JSON.stringify(req.headers, null, 2)}
`);
});
// சேவையகத்தைத் தொடங்கு
const PORT = 8080;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
// தலைப்புகளை நிரூபிக்க ஒரு கோரிக்கையைச் செய்யவும்
const req = http.request({
hostname: 'localhost',
port: PORT,
path: '/headers-demo',
method: 'GET',
headers: {
'User-Agent': 'Node.js HTTP Client',
'X-Custom-Header': 'Custom Value',
'Accept': 'text/html,application/json'
}
}, (res) => {
res.resume(); // பதில் தரவை உட்கொள்
});
req.on('error', (e) => {
console.error(`Demo request error: ${e.message}`);
});
req.end();
});
கோப்பு பதிவேற்ற எடுத்துக்காட்டு
கோப்பைப் பதிவேற்ற கோரிக்கையைப் பயன்படுத்துதல்:
const http = require('http');
const fs = require('fs');
const path = require('path');
// பதிவேற்றத்திற்கான மாதிரி கோப்பை உருவாக்கு
const sampleFile = path.join(__dirname, 'upload-sample.txt');
fs.writeFileSync(sampleFile, 'This is a sample file for upload demonstration.\n'.repeat(10));
// multipart form-data boundary மற்றும் body உருவாக்கும் செயல்பாடு
function createMultipartFormData(fields, files) {
const boundary = `----NodeJSUploadExample${Math.random().toString(16).substr(2)}`;
let body = '';
// வழக்கமான fields சேர்க்கவும்
Object.keys(fields).forEach(field => {
body += `--${boundary}\r\n`;
body += `Content-Disposition: form-data; name="${field}"\r\n\r\n`;
body += `${fields[field]}\r\n`;
});
// கோப்புகளைச் சேர்க்கவும்
Object.keys(files).forEach(fileField => {
const filePath = files[fileField];
const filename = path.basename(filePath);
const fileContent = fs.readFileSync(filePath);
body += `--${boundary}\r\n`;
body += `Content-Disposition: form-data; name="${fileField}"; filename="${filename}"\r\n`;
body += `Content-Type: application/octet-stream\r\n\r\n`;
body += fileContent.toString() + '\r\n';
});
// இறுதி boundary சேர்க்கவும்
body += `--${boundary}--\r\n`;
return {
boundary,
body
};
}
// form தரவைத் தயார் செய்யவும்
const formData = createMultipartFormData(
{
name: 'Node.js Upload Example',
description: 'Uploading a file using HTTP client request'
},
{
file: sampleFile
}
);
// கோரிக்கை விருப்பங்கள்
const options = {
hostname: 'httpbin.org',
port: 80,
path: '/post',
method: 'POST',
headers: {
'Content-Type': `multipart/form-data; boundary=${formData.boundary}`,
'Content-Length': Buffer.byteLength(formData.body)
}
};
// கோரிக்கையை உருவாக்கு
const req = http.request(options, (res) => {
console.log(`Upload Status: ${res.statusCode}`);
let responseData = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
responseData += chunk;
});
res.on('end', () => {
console.log('Upload Response:');
try {
const response = JSON.stringify(JSON.parse(responseData), null, 2);
console.log(response);
} catch (e) {
console.log(responseData);
}
// மாதிரி கோப்பை சுத்தம் செய்யவும்
fs.unlinkSync(sampleFile);
console.log('Sample file removed');
});
});
req.on('error', (e) => {
console.error(`Upload error: ${e.message}`);
});
// form தரவை அனுப்பவும்
req.write(formData.body);
req.end();
console.log('Uploading file...');
கோரிக்கை Timeouts ஐக் கையாளுதல்
கோரிக்கை timeouts ஐ அமைத்தல் மற்றும் கையாளுதல்:
const http = require('http');
// timeout உடன் ஒரு கோரிக்கையை உருவாக்கு
const req = http.request({
hostname: 'example.com',
port: 80,
path: '/',
method: 'GET',
timeout: 8080 // 3 second timeout
}, (res) => {
console.log(`STATUS: ${res.statusCode}`);
res.resume(); // பதில் தரவை உட்கொள்
});
// timeout நிகழ்வைக் கையாளவும்
req.on('timeout', () => {
console.log('Request timed out after 3 seconds');
req.abort(); // கோரிக்கையை கைவிடவும்
});
// abort() காரணமாக ஏற்படும் பிழைகள் உட்பட பிழைகளைக் கையாளவும்
req.on('error', (err) => {
console.error(`Request error: ${err.message}`);
});
// கோரிக்கையை முடி
req.end();