不廢話直接上代碼祭椰,先來一個(gè)最簡(jiǎn)單的服務(wù)器: server.js如下:
const http = require("http");
const fs=require('fs');
var server=http.createServer(function(req,res){
//http模塊的 createServer()方法用于創(chuàng)建一個(gè)http服務(wù):
//參數(shù): req,響應(yīng)請(qǐng)求:
//參數(shù): res,返回應(yīng)答:
res.write("hello nodejs");
res.end();
//這一步在瀏覽器localhost:8898打開可以看到 hello nodejs(當(dāng)然前提是node 運(yùn)行一下文件);
----分割線---
//但是這個(gè)服務(wù)器太low了,通常服務(wù)器都是可以返回文件的: 假設(shè)注釋掉上面連行代碼: 我們來看看req的用法:
//假設(shè)我們?cè)跒g覽器輸出 localhost:8898/index.html 想當(dāng)然我們是把這個(gè)頁面返回給客戶端;怎么做呢?
//req對(duì)象中,我們可以截取到 /index.html
var url=req.url // index.html 當(dāng)然如果后面有參數(shù)也是可以截取到的
//現(xiàn)在我們假設(shè)有一個(gè)www目錄在 server.js的同級(jí)目錄,www下新建 index.html ,頁面內(nèi)容自定義:
//通常的想法是:
if(url=='index.html'){
fs.readFile("www/index.html",function(err,data){
if(err){
console.log("文件讀取出錯(cuò)..")
}else{
res.write(data) //讀取html內(nèi)容頁面,并返回給前端;
}
res.end()
})
} if(url=="regester.html"){---codoe---} //就像上面這樣完成了一系列頁面的請(qǐng)求; ---就如一個(gè)系統(tǒng)有數(shù)百個(gè)頁面,這種方式就徹底o(hù)ver了,看下面方式
});
server.listen(8898)
一個(gè)服務(wù)器統(tǒng)一讀文件和接口
const http = require("http");
const urlLib = require('url');
const fs = require('fs');
const querystring = require('querystring');
// console.log(querystring.parse("username=liuhf&password=123456"));
var server = http.createServer(function (req, res) {
var obj = urlLib.parse(req.url, true);
var path = obj.pathname; //pathname; host到? 前面之間的str
var GET = {}; //測(cè)試get數(shù)據(jù);
var POST = {}; //測(cè)試post數(shù)據(jù);
if (path == '/favicon.ico') { return } //chrome 瀏覽器會(huì)自動(dòng)請(qǐng)求站點(diǎn)圖標(biāo);
GET = obj.query;
var data_str = ''; //暫時(shí)存放簡(jiǎn)單數(shù)據(jù);
//作為一個(gè)服務(wù)器,最基本的具有 處理 文件請(qǐng)求 和 接口請(qǐng)求
if (path.indexOf("api") < 0) { //是文件請(qǐng)求 //這里只是簡(jiǎn)單的舉一個(gè)例子;
//文件服務(wù)器:
fs.readFile("./www" + path, function (err, data) { //相當(dāng)于一個(gè)統(tǒng)一的映射到www目錄;
if (err) {
console.log(err);
} else {
res.write(data)
}
res.end();
});
} else {
console.log("請(qǐng)求接口--")
//接口請(qǐng)求:
req.on("data", function (data) { //僅對(duì)post數(shù)據(jù)有效;
data_str += data; //當(dāng)post數(shù)據(jù)過大的時(shí)候,會(huì)分次傳輸送;
console.log("post_data",data)
});
req.on("end", function (data) { //end '事件' 并不是post獨(dú)有,不管有沒有post數(shù)據(jù),都會(huì)進(jìn)入這里;
POST = querystring.parse(data_str)
console.log("post提交--")
console.log("GET:",GET);
console.log("POST:",POST)
res.end();
});
}
}).listen(8899);