1.什么是Node.js
1.1Node.js是一款基于“V8引擎”的javaScript運(yùn)行環(huán)境
V8引擎:V8引擎是一款專門解釋和執(zhí)行JS代碼的虛擬機(jī)统舀,任何程序只要集成了V8引擎都可以執(zhí)行JS代碼
總結(jié):Node.js不是一門語言亡问,它是一個(gè)運(yùn)行環(huán)境拔创,這個(gè)運(yùn)行環(huán)境下可以運(yùn)行我們編寫的JS代碼懒构,這個(gè)運(yùn)行環(huán)境最大的特點(diǎn)就是提供了操作“操作系統(tǒng)底層的API”碉熄,通過底層的API我們可以編寫出網(wǎng)頁中無法實(shí)現(xiàn)的功能(諸如:打包工具赂鲤,網(wǎng)站服務(wù)器等)
1.2 Node.js環(huán)境的搭建
(1)node.js官網(wǎng)地址:https://nodejs.org/zh-cn/
(2)官網(wǎng)下載msi安裝包
(3)全程下一步
(4)安裝完成后在工具中輸入 node -v
推薦借助NVM的搭建方式
(1)下載NVM:https://githup.com/coreybutler/nvm-windows
(2)創(chuàng)建一個(gè)目錄
(3)在目錄中創(chuàng)建NVM和NODE子目錄纬傲,把nvm包解壓到nvm中
(4)在install.cmd文件上面右鍵選擇(以管理員身份運(yùn)行)
在彈出來的終端中直接按下回車畸写,將彈出的文件另存為到NVM中,打開并修改root:安裝NVM的目錄腊敲,path:安裝node的文件路徑
(5)配置環(huán)境變量
1.3 NodeJS執(zhí)行javaScript代碼
(1)REPL環(huán)境:REPL(Read Eval Print Loop)击喂,直接在命令行里編寫JS代碼:打開終端,輸入node 回車
(2)以文件的形式執(zhí)行:找到j(luò)s文件路徑碰辅,打開終端:node xxx.js
(3)在開發(fā)工具中運(yùn)行
1.4 NodeJs環(huán)境和瀏覽器環(huán)境執(zhí)行JS代碼的區(qū)別
(1)內(nèi)置對(duì)象的不同:瀏覽器是window,node里的是global
(2)this默認(rèn)指向不同
瀏覽器環(huán)境:this=>window(默認(rèn))
NodeJS環(huán)境:this =>{}(默認(rèn)指向空對(duì)象)
(3)API不同
瀏覽器環(huán)境:提供了操作節(jié)點(diǎn)的DOM相關(guān)API和操作瀏覽器BOM相關(guān)的API
NodeJS環(huán)境:沒有HTML節(jié)點(diǎn)也沒有瀏覽器懂昂,NodeJs環(huán)境中沒有DOM/BOM
1.5 模塊
(1)瀏覽器開發(fā)中的模塊:在瀏覽器開發(fā)中為了避免命名沖突,方便維護(hù)等没宾,采用類或者立即執(zhí)行函數(shù)的方式來封裝代碼凌彬,這里的類或者函數(shù)就是瀏覽器開發(fā)中的一模塊(問題:人多雜亂無標(biāo)準(zhǔn))
(2)NodeJS中的模塊:nodeJs采用CommonJS規(guī)范,它規(guī)定了如何定義一個(gè)模塊榕吼,如何暴露(導(dǎo)出)模塊中的變量函數(shù)饿序,以及如何使用定義好的模塊
CommJs規(guī)范中一個(gè)文件就是一個(gè)模塊
CommJs規(guī)范中每個(gè)文件中的變量函數(shù)都是私有的,對(duì)其他文件不可見
CommJs規(guī)范中每個(gè)文件中的變量函數(shù)必須通過exports暴露之后才能使用
CommJs規(guī)范中想要使用其它文件暴露的變量函數(shù)必須通過require()導(dǎo)入模塊才可以使用
1.6 NodeJs全局屬性和方法
(1)_dirname:被執(zhí)行的JS文件所在的目錄 D:\dev\study
(2)_filename:被執(zhí)行的JS文件的絕對(duì)路徑 D:\dev\study\xxx.js
(3)定時(shí)器:setInterval setTimeout cleanInterval cleanTimeout
(4)exports:導(dǎo)出
(5)module.exports:導(dǎo)出
(6)require():導(dǎo)入
(7)全局對(duì)象導(dǎo)出 globle.xxx =xxx 但是使用必須通過require導(dǎo)入
(8)exports和module.exports的區(qū)別
exports =xxx:此時(shí)拿到的是一個(gè)空對(duì)象羹蚣,不可以直接賦值
module.exports = xxx :能夠拿到具體的值原探,可以直接賦值
1.7 require導(dǎo)入注意點(diǎn)
(1)require()導(dǎo)入模塊是可以不添加導(dǎo)入模塊的類型,如果沒有指定導(dǎo)入模塊的類型顽素,那么會(huì)依次查找.js .json .node文件咽弦,無論哪三種類型,導(dǎo)入之后都會(huì)轉(zhuǎn)換成JS對(duì)象返回給我們
(2)導(dǎo)入自定義模塊時(shí)必須指定路徑(./xxx)胁出,require()可以導(dǎo)入“自定義模塊型型、系統(tǒng)模塊、第三方模塊”全蝶,導(dǎo)入自定義模塊時(shí)必須加上路徑闹蒜,導(dǎo)入系統(tǒng)模塊和第三方模塊時(shí)不用添加路徑
1.8 Node包和包管理
(1)簡(jiǎn)而言之:一個(gè)模塊就是一個(gè)單獨(dú)的文件,一個(gè)包中可以有一個(gè)或多個(gè)模塊
(2)NodeJS包管理:在NodeJS中為了方便開發(fā)人員發(fā)布抑淫、安裝和管理绷落,NodeJS推出了一個(gè)包管理工具NPM(Node Package Manager),NPM不需要單獨(dú)安裝,只要搭建好NodeJS環(huán)境就自動(dòng)安裝好了始苇。
2.NPM使用
2.1全局安裝
(1)npm install list :查看npm的基本配置
(2)npm install -g nrm 安裝nrm 安裝最新版本
(3)npm uninstall -g nrm 卸載nrm
(4)npm install -g nrm@xxx 安裝指定版本
(5)npm update -g nrm 更新指定的包到最新版本
2.2本地安裝
本地安裝:一般用于安裝當(dāng)前項(xiàng)目使用的包砌烁,存儲(chǔ)在當(dāng)前項(xiàng)目node_modules中
(1)npm init -y 初始化package.json文件
(2)npm install 安裝所有的包
(3)npm install --production 只會(huì)安裝dependencies中的包
(4)npm install --development 只會(huì)安裝devDependencies中的包
2.3.NRM使用
(1)全局安裝nrm:npm install -g nrm
(2)nrm --version 查看nrm的版本
(3)nrm ls 查看允許切換的資源地址
(4)nrm use taobao 將下載地址切換到淘寶
(5)切換以后還是通過npm指令進(jìn)行安裝
2.4.CNPM使用
(1)npm install cnpm -g -registry://registry.npm.taobao.org
(2)個(gè)人不推薦.....
2.5.Yarn使用
(1)npm install -g yarn
(2)yarn --versin
(3)yarn add xxx 安裝xxx 默認(rèn)安裝到dependencies
(4)yarn add --save 安裝到dependencies
(5)yarn add --dev 安裝到devDependencies
(6)yarn remove xxx 卸載xxx依賴
(7)yarn upgrade add xxx 更新xxx版本
3.NodeJs核心API
(1)Buffer類
Buffer是NodeJs全局對(duì)象上的一個(gè)類,是一個(gè)專門用于存儲(chǔ)字節(jié)數(shù)據(jù)的類
1.創(chuàng)建一個(gè)Buffer對(duì)象
Buffer.alloc(size,fill,encoding) size:長(zhǎng)度 fill:填充數(shù) encoding:編碼
let str = Buffer.alloc(3)
console.log(str);//<Buffer 00 00 00>
注意點(diǎn):通過console.log輸出Buffer,會(huì)自動(dòng)將存儲(chǔ)的內(nèi)容轉(zhuǎn)換成16進(jìn)制再輸出催式。
let buf = Buffer.alloc(3,17);
console.log(buf);//<Buffer 11 11 11>
2.根據(jù)數(shù)組/字符串創(chuàng)建一個(gè)Buffer對(duì)象
Buffer.from(string,encoding)
如: let buf = Buffer.from("abc");
console.log(buf);//<Buffer 61 62 63>
let buf2 = Buffer.from([1,3,5]);
3.Buffer對(duì)象的本質(zhì)就是一個(gè)數(shù)組
4.toString()
5.write(data,offset,length,encoding)
data:寫入的數(shù)據(jù)
offset:從哪兒開始寫入
length:寫入的長(zhǎng)度
encoding:默認(rèn)utf-8
6.slice(n,m)
n:從索引n開始截取
m:截取到索引m(不包含索引m的值)
7.isEncoding()//檢查Buffer是否支持某種編碼格式
let res = Buffer.isEncoding("utf8")
console.log(res);//true
8.isBuffer()//檢查是否是Buffer類型對(duì)象
let obj = {};
let res =Buffer.isBuffer(obj);
console.log(res);//false
9.byteLength();//獲取Buffer實(shí)際字節(jié)長(zhǎng)度
let buf = Buffer.from("123");
let buf2 = Buffer.from("秋風(fēng)")函喉;
let res = Buffer.byteLength(buf);//3
let res2 = Buffer.byteLength(buf2);//6
10.concat([a1,a2]);//合并Buffer中的數(shù)據(jù)
let buf1 = Buffer.from("123");
let buf2 = Buffer.from("abc");
let buf3 = Buffer.from("xxx");
let res = Buffer.concat([buf1, buf2, buf3]);
console.log(res);
console.log(res.toString());//123abcxxx
(2)Path 路徑模塊
Path和Buffer一樣,都是NodeJS中一個(gè)特殊的模塊,不同的是Buffer模塊已經(jīng)添加到Global上了, 所以不需要手動(dòng)導(dǎo)入而Path模塊沒有添加到Global上, 所以使用荣月,時(shí)需要手動(dòng)導(dǎo)入
let path = require("path");
1.basename用于獲取路徑的最后一個(gè)組成部分
let res = path.basename('/a/b/c/d/index.html');
let res = path.basename('/a/b/c/d');
let res = path.basename('/a/b/c/d/index.html', ".html");
console.log(res);
2.dirname用于獲取路徑中的目錄, 也就是除了最后一個(gè)部分以外的內(nèi)容
let res = path.dirname('/a/b/c/d/index.html');
let res = path.dirname('/a/b/c/d');
console.log(res);
3.extname用于獲取路徑中最后一個(gè)組成部分的擴(kuò)展名
let res = path.extname('/a/b/c/d/index.html');
let res = path.extname('/a/b/c/d');
console.log(res);
4.isAbsolute用于判斷路徑是否是一個(gè)絕對(duì)路徑
注意點(diǎn):區(qū)分操作系統(tǒng)
在Linux操作系統(tǒng)中/開頭就是絕對(duì)路徑
在Windows操作系統(tǒng)中盤符開頭就是絕對(duì)路徑
在Linux操作系統(tǒng)中路徑的分隔符是左斜杠 /
在Windows操作系統(tǒng)中路徑的分隔符是右斜杠 \
let res = path.isAbsolute('/a/b/c/d/index.html'); // true
let res = path.isAbsolute('./a/b/c/d/index.html'); // false
let res = path.isAbsolute('c:\\a\\b\\c\\d\\index.html'); // true
let res = path.isAbsolute('a\\b\\c\\d\\index.html'); // false
console.log(res);
5.path.sep用于獲取當(dāng)前操作系統(tǒng)中路徑的分隔符的
如果是在Linux操作系統(tǒng)中運(yùn)行那么獲取到的是 左斜杠 /
如果是在Windows操作系統(tǒng)中運(yùn)行那么獲取到的是 右斜杠 \
console.log(path.sep);
6.path.delimiter用于獲取當(dāng)前操作系統(tǒng)環(huán)境變量的分隔符的
如果是在Linux操作系統(tǒng)中運(yùn)行那么獲取到的是 :
如果是在Windows操作系統(tǒng)中運(yùn)行那么獲取到的是 ;
console.log(path.delimiter);
7.path.parse(path): 用于將路徑轉(zhuǎn)換成對(duì)象
let obj = path.parse("/a/b/c/d/index.html");
console.log(obj);
/*{
root: '/',
dir: '/a/b/c/d',
base: 'index.html',
ext: '.html',
name: 'index'
}*/
8.path.format(pathObject): 用于將對(duì)象轉(zhuǎn)換成路徑
let obj = {
root: '/',
dir: '/a/b/c/d',
base: 'index.html',
ext: '.html',
name: 'index'
}
let newPath = path.format(obj)
console.log(obj);//"/a/b/c/d/index.html"
9.path.join([...paths]): 用于拼接路徑
注意點(diǎn):如果參數(shù)中沒有添加/, 那么該方法會(huì)自動(dòng)添加,如果參數(shù)中有..,
那么會(huì)自動(dòng)根據(jù)前面的參數(shù)生成的路徑, 去到上一級(jí)路徑
let str = path.join("/a/b", "c"); // /a/b/c
let str = path.join("/a/b", "/c"); // /a/b/c
let str = path.join("/a/b", "/c", "../"); // /a/b/c --> /a/b
let str = path.join("/a/b", "/c", "../../"); // /a/b/c --> /a
console.log(str);
10.path.normalize(path): 用于規(guī)范化路徑
let res = path.normalize("/a//b///c////d/////index.html");
console.log(res);//'/a/b/c/d/index.html'
11.path.relative(from, to): 用于計(jì)算相對(duì)路徑
第一個(gè)參數(shù): /data/orandea/test/aaa
第二個(gè)參數(shù): /data/orandea/impl/bbb
/data/orandea/test/aaa --> ../ --> /data/orandea/test
/data/orandea/test --> ../ --> /data/orandea
let res = path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
console.log(res);//..\..\impl\bbb
12.path.resolve([...paths]): 用于解析路徑
注意點(diǎn): 如果后面的參數(shù)是絕對(duì)路徑, 那么前面的參數(shù)就會(huì)被忽略
let res = path.resolve('/foo/bar', './baz'); // /foo/bar/baz
let res = path.resolve('/foo/bar', '../baz'); // /foo/baz
let res = path.resolve('/foo/bar', '/baz'); // /baz
console.log(res);
(3) fs 文件模塊
1.fs :文件模塊:封裝了各種文件相關(guān)的操作
2.查看文件的狀態(tài)
fs.stat(path,options,callback);//異步獲取
fs.statSync(path,options);//同步獲取
let fs = require("fs");
fs.stat(__dirname,function(err,stats){
console.log(stats);
//stats對(duì)象中包含:
//birthime:文件創(chuàng)建的時(shí)間
//mtime:文件中內(nèi)容發(fā)生變化管呵,被修改的時(shí)間
if(stats.isFile()){
//isFile():判斷是否是一個(gè)文件
console.log("當(dāng)前路徑對(duì)應(yīng)的是一個(gè)文件");
}else if(stats.isDirectory(){
//isDirectory():判斷是否是一個(gè)目錄
console.log("當(dāng)前路徑對(duì)應(yīng)的是一個(gè)目錄")哺窄;
}
})
let stats = fs.statSync(__dirname);
console.log(stats);
3.文件的讀取 fs.readFile(path,options,callback);fs.readFileSync(path,options)
注意點(diǎn):沒有指定第二個(gè)參數(shù)撇寞,默認(rèn)會(huì)將讀取到的數(shù)據(jù)放到Buffer中
第二參數(shù)指定為utf8顿天,返回的數(shù)據(jù)就是字符串
let fs = require("fs");
let path = require("path");
let str = path.join(__dirname,"data.txt");//拿到需要讀取的文件路徑
fs.readFile(str,"utf-8",function(err,data){
if(err){
throw new Error("讀取文件失敗")堂氯;
}
console.log(data);
console.log(data.toString());
})
let data = fs.readFileSync(str,"utf-8");
console.log(data);
4.文件的寫入 fs.writeFile(file,data,callback);fs.writeFileSync(file,options);
let fs = require("fs");
let path = require("path");
let str = path.join(__dirname,"luchunqiong.txt");//拼接寫入的路徑
fs.writeFile(str,"www.luchunqiong.com","utf-8",function(err){...});
let buf = Buffer.from("www.luchunqiong");
fs.writeFile(str,buf,"utf-8",function(err){
if(err){
throw new Error("寫入數(shù)據(jù)錯(cuò)誤")蔑担;
}else{
console.log("寫入數(shù)據(jù)成功");
}
})
// let res = fs.writeFileSync(str, "www.luchunqiong.com", "utf-8");
// console.log(res);
注意點(diǎn)://writeFile()和writeFileSync()寫入數(shù)據(jù)后會(huì)覆蓋以前的數(shù)據(jù)
//如果是追加:必須用appendFile()和appendFileSync();
注意點(diǎn)://前面的方法關(guān)于文件的寫入和讀取操作都是一次性將數(shù)據(jù)讀入內(nèi)存或者一次性寫入到
//文件中咽白,但是如果數(shù)據(jù)比較大啤握,直接將所有數(shù)據(jù)都讀到內(nèi)存中會(huì)導(dǎo)致計(jì)算機(jī)內(nèi)存爆炸
//卡頓,死機(jī)等晶框,所以對(duì)于比較大的文件我們需要分批讀取和寫入
//fs.createReadStream(path,options);fs.createWriteStream(path,options)
let fs = require("fs");
let path = require("path");
//拼接讀取的路徑
let str = path.join(__dirname,"luchunqiong.txt");
//創(chuàng)建一個(gè)讀取流
let readStream = fs.createReadStream(str,{
encoding:"utf-8"排抬,//文件讀取的編碼格式
highWaterMark:1 //每次讀取的大小
})
//添加事件監(jiān)聽
readStream.on("open",function(){
console.log("表示數(shù)據(jù)流和文件建立了關(guān)系");
})授段;
readStream.on("error",function(){
console.log("表示數(shù)據(jù)流和文件建立關(guān)系失敗")蹲蒲;
});
readStream.on("data",function(){
console.log("表示通過讀取流從文件中讀取到了數(shù)據(jù)",data)侵贵;
});
readStream.on("close",function(){
console.log("表示數(shù)據(jù)流斷開了和文件的關(guān)系届搁,并且數(shù)據(jù)已經(jīng)讀取完畢")窍育;
})
//拼接寫入的路徑
let str = path.join(__dirname,"zhouhong.txt");
//創(chuàng)建一個(gè)寫入流
let writeStream = fs.createWriteStream(str,{
encoding:"utf-8"
});
//監(jiān)聽寫入流的事件
writeStream.on("open", function () {
console.log("表示數(shù)據(jù)流和文件建立關(guān)系成功");
});
writeStream.on("error", function () {
console.log("表示數(shù)據(jù)流和文件建立關(guān)系失敗");
});
writeStream.on("close", function () {
console.log("表示數(shù)據(jù)流斷開了和文件的關(guān)系");
});
let data = "www.it666.com";
let index = 0;
let timerId = setInterval(function () {
let ch = data[index];
index++;
writeStream.write(ch);
console.log("本次寫入了", ch);
if(index === data.length){
clearInterval(timerId);
writeStream.end();
}
}, 1000);
//1.生成讀取和寫入的路徑
let readPath = path.join(__dirname,"canjinkong.mp4");
let writePath = path.join(__dirname,"yanmi.mp4");
//2.創(chuàng)建一個(gè)讀取流和寫入流
let readStream = fs.createReadStream(readPath);
let writeStream = fs.createWriteStream(writePath)表锻;
//3.監(jiān)聽讀取流事件
readStream.on("open", function () {
console.log("表示數(shù)據(jù)流和文件建立關(guān)系成功");
});
readStream.on("error", function () {
console.log("表示數(shù)據(jù)流和文件建立關(guān)系失敗");
});
readStream.on("data", function (data) {
// console.log("表示通過讀取流從文件中讀取到了數(shù)據(jù)", data);
writeStream.write(data);
});
readStream.on("close", function () {
console.log("表示數(shù)據(jù)流斷開了和文件的關(guān)系, 并且數(shù)據(jù)已經(jīng)讀取完畢了");
writeStream.end();
});
//監(jiān)聽寫入流事件
writeStream.on("open", function () {
console.log("表示數(shù)據(jù)流和文件建立關(guān)系成功");
});
writeStream.on("error", function () {
console.log("表示數(shù)據(jù)流和文件建立關(guān)系失敗");
});
writeStream.on("close", function () {
console.log("表示數(shù)據(jù)流斷開了和文件的關(guān)系");
});
// 1.生成讀取和寫入的路徑
let readPath = path.join(__dirname, "test.mp4");
let writePath = path.join(__dirname, "abc.mp4");
// 2.創(chuàng)建一個(gè)讀取流
let readStream = fs.createReadStream(readPath);
// 3.創(chuàng)建一個(gè)寫入流
let writeStream = fs.createWriteStream(writePath);
// 利用讀取流的管道方法來快速的實(shí)現(xiàn)文件拷貝
readStream.pipe(writeStream);
目錄操作
1)、創(chuàng)建目錄
fs.mkdir(path, callback)
fs.mkdirSync(path)
2)确镊、讀取目錄
fs.readdir(path,options, callback)
fs.readdirSync(path,options)
3)、刪除目錄
fs.rmdir(path, callback)
fs.rmdirSync(path)
練習(xí):利用NodeJS生成項(xiàng)目模板
projectName
|---images
|---css
|---js
|---index.html
let fs = require("fs");
let path = require("path");
class CreatProject {
constructor(rootPath,projectName){
this.rootPath = rootPath;
this.projectName = projectName;
this.subFils = ["images","css","js","index.html"];
}
initProject(){
let projectPath = path.join(this.rootPath,this.projectName);
this.subFils.forEach(fileName =>{
if(path.extname(fileName) ===""){
let dirPath = path.join(projectPath,fileName);
fs.mkdirSync(dirPath);
}else{
let filePath = path.join(projectName,fileName);
fs.writeFileSync(filePath,"");
}
})
}
}
let projectNode = new CreateProject(__dirname, "taobao");
projectNode.initProject();
(4)HTTP模塊
HTTP模塊:通過Nodejs提供的http模塊,我們可以快速的構(gòu)建一個(gè)web服務(wù)器,接收瀏覽器請(qǐng)求契沫、響應(yīng)瀏覽器請(qǐng)求等
(1)WEB服務(wù)器的搭建
步驟: 1).導(dǎo)入HTTP模塊
2).創(chuàng)建服務(wù)器實(shí)例對(duì)象
3).綁定請(qǐng)求事件
4).監(jiān)聽指定端口請(qǐng)求
let http = require("http");
let server = http.createSever();
server.listen(3000);
server.on("request",function(req,res){
//writeHead:告訴瀏覽器返回的數(shù)據(jù)是什么類型的懈万,返回的數(shù)據(jù)需要用什么字符集來解析
res.writeHead(200,{
"Content-Type":"text/plain:charset = utf=8"
});
res.end("盧春瓊")会通;//end:結(jié)束本次請(qǐng)求并且返回?cái)?shù)據(jù)
})
鏈?zhǔn)骄幊蹋? http.createServer(function(req,res){
res.writeHead(200,{
"Content-Type":"text/plain:charse=utf-8"
});
res.send("www.luchunqiong.com");
}).listen(3000);
(2)路徑分發(fā)
路徑分發(fā)也稱為路由涕侈,就是根據(jù)不同的請(qǐng)求路徑返回不同的數(shù)據(jù)。
通過請(qǐng)求監(jiān)聽方法中的request對(duì)象木张,就可以獲取到當(dāng)前請(qǐng)求的路徑端三,通過判斷請(qǐng)求路徑的
地址就可以實(shí)現(xiàn)不同的請(qǐng)求路徑返回不同的數(shù)據(jù)妻献。
let http = require("http");
let server = http.createServer();
server.listen(3000);
server.on("request",function(req,res){
res.writeHead(200,{
"Content-Type":"text/plain; charset = utf-8"
});
if(req.url.startWith("/index")){
/*res.end("首頁1")旋奢;//如果通過end方法返回?cái)?shù)據(jù),那么只會(huì)返回一次*/
res.write("首頁2")锹引;//write方法返回?cái)?shù)據(jù),可返回多次腾啥,但是write方法不具備結(jié)束請(qǐng)求功能冯吓,需要手動(dòng)結(jié)束
res.end();
}else if(req.url.startWith("/login")){
res.end("登錄");
}else{
res.end("沒有數(shù)據(jù)")组贺;
}
});
(3)獲取GET請(qǐng)求傳遞的參數(shù) url.parse()和url.format()
let url = require("url");
let http = require("http");
let server = http.createServer();
server.on("request",function(req,res){
let obj = url.parse(req.url,true);
res.end(obj.query.xxx);//在get傳參中使用query對(duì)象下xxx獲取
});
server.listen(3000);
(4)獲取post請(qǐng)求傳遞的參數(shù)
let http = require("http");
let queryString = require("querystring");
let server = http.createServer();
server.on("request",function(req,res){
let params = "";
req.on("data",function(chunk){
params += chunk; //在nodeJs中啊奄,post請(qǐng)求的參數(shù)我們不能一次性拿到渐苏,必須分批獲取
});
req.on("end",function(){
let obj = queryString.parse(params);
res.end(obj.xxx);
})
})
server.listen(3000)
(5) 服務(wù)端區(qū)分GET和POST;通過HTTP模塊中的IncomingMessage類中的method屬性
let http = require("http");
let server = http.createServer();
server.on("request",function(req,res){
res.writeHead(200,{
"Content-Type":"text/plain;charset = utf-8"
});
if(req.method.toLowerCase() === "get"){
res.end("利用GET請(qǐng)求的方式處理參數(shù)")菇夸;
}else if(req.method.toLowerCase() === "POST"){
res.end("利用post請(qǐng)求的方式處理參數(shù)")
}
})
server.listen(3000)