NodeJS http模塊用法示例【創(chuàng)建web服務(wù)器/客戶端】
本文實(shí)例講述了NodeJS http模塊用法。分享給大家供大家參考,具體如下:
Node.js提供了http模塊,用于搭建HTTP服務(wù)端和客戶端。
創(chuàng)建Web服務(wù)器
/**
* node-http 服務(wù)端
*/
let http = require('http');
let url = require('url');
let fs = require('fs');
// 創(chuàng)建服務(wù)器
let server = http.createServer((req, res) => {
// 解析請求
let pathname = url.parse(req.url).pathname; // 形如`/index.html`
console.log('收到對文件 ' + pathname + '的請求');
// 讀取文件內(nèi)容
fs.readFile(pathname.substr(1), (err, data) => {
if (err) {
console.log('文件讀取失敗:' + err);
// 設(shè)置404響應(yīng)
res.writeHead(404, {
'Content-Type': 'text/html'
});
}
else {
// 狀態(tài)碼:200
res.writeHead(200, {
'Content-Type': 'text/html'
});
// 響應(yīng)文件內(nèi)容
res.write(data.toString());
}
// 發(fā)送響應(yīng)
res.end();
});
});
server.listen(8081);
console.log('服務(wù)運(yùn)行在:http://localhost:8081,請?jiān)L問:http://localhost:8081/index.html');
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Node http</title> </head> <body> <h1>Hi~</h1> </body> </html>
運(yùn)行server.js,打開瀏覽器訪問。
創(chuàng)建客戶端
client.js
/**
* node http 創(chuàng)建客戶端
*/
let http = require('http');
// 請求選項(xiàng)
let options = {
host: 'localhost',
port: '8081',
path: '/index.html'
};
// 處理響應(yīng)的回調(diào)函數(shù)
let callback = (res) => {
// 不斷更新數(shù)據(jù)
let body = '';
res.on('data', (data) => {
body += data;
});
res.on('end', () => {
console.log('數(shù)據(jù)接收完成');
console.log(body);
});
}
// 向服務(wù)端發(fā)送請求
let req = http.request(options, callback);
req.end();
運(yùn)行server.js,再運(yùn)行client.js。
希望本文所述對大家node.js程序設(shè)計(jì)有所幫助。
相關(guān)文章
淺談NodeJs之?dāng)?shù)據(jù)庫異常處理
這篇文章主要介紹了淺談NodeJs之?dāng)?shù)據(jù)庫異常處理,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10
詳解Wondows下Node.js使用MongoDB的環(huán)境配置
這篇文章主要介紹了詳解Wondows下Node.js使用MongoDB的環(huán)境配置,這里使用到了Mongoose驅(qū)動(dòng)來讓JavaScript操作MongoDB,需要的朋友可以參考下2016-03-03
Nodejs 數(shù)組的隊(duì)列以及forEach的應(yīng)用詳解
這篇文章主要介紹了Nodejs 數(shù)組的隊(duì)列以及forEach的應(yīng)用詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02
使用Jasmine和Karma對AngularJS頁面程序進(jìn)行測試
這篇文章主要介紹了使用Jasmine和Karma對AngularJS頁面程序進(jìn)行測試的方法,以Node.js為環(huán)境,非常適合JavaScript的全棧開發(fā)時(shí)使用,需要的朋友可以參考下2016-03-03
Nodejs實(shí)現(xiàn)爬蟲抓取數(shù)據(jù)實(shí)例解析
這篇文章主要介紹了Nodejs實(shí)現(xiàn)爬蟲抓取數(shù)據(jù)實(shí)例解析,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2018-07-07
nodejs實(shí)現(xiàn)的簡單web服務(wù)器功能示例
這篇文章主要介紹了nodejs實(shí)現(xiàn)的簡單web服務(wù)器功能,結(jié)合實(shí)例形式分析了nodejs構(gòu)建web服務(wù)器的相關(guān)監(jiān)聽、響應(yīng)、數(shù)據(jù)處理等操作技巧,需要的朋友可以參考下2018-03-03

