Node-Web模块
生活随笔
收集整理的這篇文章主要介紹了
Node-Web模块
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
創(chuàng)建服務(wù)端------------------------------------------------------var http = require('http');
var fs = require('fs');
var url = require('url');// 創(chuàng)建服務(wù)器
http.createServer( function (request, response) { // 解析請求,包括文件名var pathname = url.parse(request.url).pathname;// 輸出請求的文件名console.log("Request for " + pathname + " received.");// 從文件系統(tǒng)中讀取請求的文件內(nèi)容fs.readFile(pathname.substr(1), function (err, data) {if (err) {console.log(err);// HTTP 狀態(tài)碼: 404 : NOT FOUND// Content Type: text/htmlresponse.writeHead(404, {'Content-Type': 'text/html'});}else{ // HTTP 狀態(tài)碼: 200 : OK// Content Type: text/htmlresponse.writeHead(200, {'Content-Type': 'text/html'}); // 響應(yīng)文件內(nèi)容response.write(data.toString()); }// 發(fā)送響應(yīng)數(shù)據(jù)response.end();});
}).listen(8080);// 控制臺會輸出以下信息
console.log('Server running at http://127.0.0.1:8080/');創(chuàng)建客戶端------------------------------------------------------
var http = require('http');// 用于請求的選項(xiàng)
var options = {host: 'localhost',port: '8080',path: '/index.html'
};// 處理響應(yīng)的回調(diào)函數(shù)
var callback = function(response){// 不斷更新數(shù)據(jù)var body = '';response.on('data', function(data) {body += data;});response.on('end', function() {// 數(shù)據(jù)接收完成console.log(body);});
}
// 向服務(wù)端發(fā)送請求
var req = http.request(options, callback);
req.end();
?
總結(jié)
以上是生活随笔為你收集整理的Node-Web模块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: node-OSDomainNetPath
- 下一篇: Node-Web应用框架Express