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) => {
// 解析請(qǐng)求
let pathname = url.parse(req.url).pathname; // 形如`/index.html`
console.log('收到對(duì)文件 ' + pathname + '的請(qǐng)求');
// 讀取文件內(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,請(qǐng)?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');
// 請(qǐng)求選項(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ā)送請(qǐng)求
let req = http.request(options, callback);
req.end();
運(yùn)行server.js,再運(yùn)行client.js。
希望本文所述對(duì)大家node.js程序設(shè)計(jì)有所幫助。
相關(guān)文章
xtemplate node.js 的使用方法實(shí)例解析
這篇文章主要介紹了xtemplate node.js 的使用方法實(shí)例說明,非常不錯(cuò),介紹的非常詳細(xì),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-08-08
NodeJS落地WebSocket實(shí)踐前端架構(gòu)師破局技術(shù)
這篇文章主要為大家介紹了NodeJS落地WebSocket實(shí)踐前端架構(gòu)師破局技術(shù),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
解決Node.js包管理器安裝報(bào)錯(cuò)npm?ERR!?code?1的問題
在開發(fā)過程中,我們經(jīng)常需要使用各種Node.js包來擴(kuò)展我們的應(yīng)用程序功能,這些包通常通過npm(Node.js包管理器)進(jìn)行安裝和管理,有時(shí)候我們可能會(huì)遇到一些關(guān)于npm的錯(cuò)誤,本文將詳細(xì)介紹如何解決這個(gè)問題,并提供一個(gè)詳細(xì)的實(shí)例,需要的朋友可以參考下2024-03-03
利用nodeJs anywhere搭建本地服務(wù)器環(huán)境的方法
今天小編就為大家分享一篇利用nodeJs anywhere搭建本地服務(wù)器環(huán)境的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-05-05
如何在NestJS中添加對(duì)Stripe的WebHook驗(yàn)證詳解
這篇文章主要為大家介紹了如何在NestJS中添加對(duì)Stripe的WebHook驗(yàn)證詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08

