一.定義:運行在服務(wù)端的js
二.使用:
node -v//檢測版本
e://切換到e盤
cd 文件名//進入文件夾
node js文件//執(zhí)行某個文件
三.http創(chuàng)建服務(wù)器
//創(chuàng)建一個簡單的服務(wù)器
//1.引入http模塊
var http=require('http');
//2.使用http模塊創(chuàng)建一個服務(wù)
var server=http.createServer(function(req,res){
console.log('服務(wù)器開啟');
/* if(req.url=='/1.html'){
res.write('111111');
}else if(req.url=='/2.html'){
res.write('2222');
}else{
res.write('404');//響應(yīng)的內(nèi)容
}*/
switch(req.url){//獲取請求路徑
case '/1.html':
res.write('1111111');
break;
case '/2.html':
res.write('2222222');
break;
default:
res.write('404');
}
//兩個響應(yīng)方式
/*res.write('succ');*///響應(yīng)的內(nèi)容
res.end();//響應(yīng)結(jié)束
})
//3.監(jiān)聽一個端口號
server.listen(8080);
四.fs模塊 讀取文件 寫文件
GET方式
// http fs 接受前端傳過來的數(shù)據(jù)請求
// get post ajax form 后臺:轉(zhuǎn)換成對象
// form表單發(fā)送數(shù)據(jù) 轉(zhuǎn)換對象格式
//uname=jack&upwd=123 {uname:jack,upwd:123}
const http=require('http');
var server=http.createServer(function(req,res){
var GET={};
//獲取提交的url
// console.log(req.url);// /?uname=jack&upwd=123
var arr=req.url.split('?');//['/','uname=jack&upwd=123']
var arr1=arr[1].split('&');//['uname=jack',upwd=123]
for(var i=0;i<arr1.length;i++){
var arr2=arr1[i].split('=');//['uname','jack'] ['upwd','123']
GET[arr2[0]]=arr2[1];
console.log(GET);
}
});
server.listen(8080);
POST方式
// get post
// 1.手動 2.queryString 3.url
//post : get傳輸數(shù)據(jù)量小 post傳輸?shù)臄?shù)據(jù)量大
const http=require('http');
const queryString=require('querystring')
var server=http.createServer(function(req,res){
var str='';
req.on('data',function(data){//每次發(fā)送的數(shù)據(jù) data代表每次發(fā)送的數(shù)據(jù)
//小段數(shù)據(jù) data data data
str+=data;
})
req.on('end',function(){//數(shù)據(jù)已經(jīng)發(fā)送結(jié)束
var post=queryString.parse(str);
console.log(post);//uname=jack&upwd=123
})
});
server.listen(8080);