核心模塊——http

http模塊API內(nèi)容也不是很多,主要有http.server、http.ClientRequest、http.ServerResponse、http.IncomingMessage四個(gè)類(lèi)

一、http.server

服務(wù)器類(lèi),創(chuàng)建一個(gè)服務(wù)器對(duì)象的方法如下:

const http = require('http');
const server = http.createServer((req, res) => { 
  //req即是http.IncomingMessage類(lèi)
  //res是http.ServerResponse類(lèi)
 res.end();
});
server.listen(8000);

這就創(chuàng)建了一個(gè)服務(wù)器,監(jiān)聽(tīng)8000端口,127.0.0.1:8000,createServer方法的回調(diào)函數(shù)用于監(jiān)聽(tīng)server的request事件

二、http.IncomingMessage

上例中的req繼承自此類(lèi),主要用于獲取請(qǐng)求信息,屬性如下:

request

現(xiàn)在自己用到了標(biāo)出的這幾個(gè),
req.url獲取鏈接中的path部分,搭配URL模塊可以輕松獲取get請(qǐng)求的查詢(xún)字符串

三、http.ServerResponse

例子中的res,用于響應(yīng)客戶(hù)端請(qǐng)求

response
var http = require('http');

http.createServer(function (request, response) {
    response.writeHead(200, { 'Content-Type': 'text-plain' });
    response.write('Hello ');
    response.end('World\n');
}).listen(8000);
四、http.ClientRequest

這是我理解為后端代理,用于在服務(wù)器發(fā)送請(qǐng)求,可以用這個(gè)寫(xiě)個(gè)小爬蟲(chóng)程序

  • http.get(options[, callback])
    發(fā)送get請(qǐng)求,不需要有請(qǐng)求體
http.get('http://www.google.com/index.html', (res) => { 
  console.log(`Got response: ${res.statusCode}`); // consume  response body
  res.resume();
})
.on('error', (e) => { 
  console.log(`Got error: ${e.message}`);
});

此處的res是用于接收另一個(gè)服務(wù)端的響應(yīng),而不是去響應(yīng),可以堪稱(chēng)這個(gè)時(shí)候有點(diǎn)類(lèi)似http.IncomingMessage(當(dāng)然這完全不是一回事)

  • http.request(options[, callback])
    用于發(fā)送post請(qǐng)求,由于post請(qǐng)求需要有請(qǐng)求體,參數(shù)就復(fù)雜多了,官網(wǎng)的例子:
var postData = querystring.stringify({ 'msg' : 'Hello World!'});
var options = { 
    hostname: 'www.google.com', port: 80, 
    path: '/upload', 
    method: 'POST', 
    headers: { 
        'Content-Type': 'application/x-www-form-urlencoded', 
        'Content-Length': Buffer.byteLength(postData) }
 };
var req = http.request(options, (res) => {
     console.log(`STATUS: ${res.statusCode}`); 
     console.log(`HEADERS: ${JSON.stringify(res.headers)}`); 
     res.setEncoding('utf8'); 
     res.on('data', (chunk) => {
       console.log(`BODY: ${chunk}`); 
     }); 
     res.on('end', () => {
       console.log('No more data in response.') 
     })
});
req.on('error', (e) => { 
    console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容