HTTP請求與路由
阿新 • • 發佈:2021-02-05
技術標籤:javascriptnode.js
4.1請求引數
客戶端向伺服器端傳送請求時,有時需要攜帶一些客戶資訊,客戶資訊需要通過請求引數的形式傳遞到伺服器端,比如登入操作。
4.2GET請求引數
引數被放置在瀏覽器位址列中,例如:http://localhost:3000/?name=zhangsan&age=20
//node.js中的模組
const url = require('url');
url.parse(req.url,true).query;
//1.第一個引數要解析的url地址
//2.第二個將查詢引數解析成物件形式
//物件解構
let { query, pathname } = url. parse(req.url,true);
4.3POST請求引數
引數被放置在請求體中進行傳輸;
獲取POST引數需要使用data事件和end事件;
使用querystring系統模組將引數轉換為物件格式;
const http = require('http');
const app = http.ceateServe();
//node中處理請求引數模組
const querystring = require('querystring');
app.on('request',(req,res) => {
//post引數是通過事件的方式接收的
//data事件 當請求引數傳遞的時候觸發data事件
//end事件 當引數傳遞完成的時候觸發end事件
let postParams = '';
//監聽引數傳輸事件
req.on('data',(params) => {
postParams += params;
});
//監聽引數傳輸完畢事件
req.on('end',() => {
//字串引數處理成物件格式
let postParams = querystring.parse(postParams);
console.log(postParams);
});
req.end('ok');
})
4.4路由
路由是指客戶端請求地址與伺服器端程式程式碼的對應關係,簡單來說,就是請求什麼響應什麼。
//當客戶端發來請求的時候
app.on('request',(req,res) => {
//獲取客戶端的請求路徑
let{ pathname } = url.parse(req.url);
if(pathname = '/' || pathname == '/index') {
res.end('首頁');
} else if (pathname == '/list') {
res.end('列表頁');
} else {
res.end('抱歉,您訪問的頁面錯誤');
}
})
//1.引入系統模組http
//2.建立網站伺服器
//3.為網站伺服器物件新增請求事件
//4.實現路由功能
// 1.獲取客戶端的請求方式
// 2.獲取客戶端的請求地址
const http = require('http');
const url = require('url');
const app = http.createServer();
app.on('request',(req,res) => {
//獲取請求方式
const method = req.method.toLowerCase();
//獲取請求地址
const pathname = url.parse(req.url).pathname;
//防止網頁亂碼
res.writeHead(200,{
'content-type':'text/html;charset=utf8'
});
if(method = 'get'){
if(pathname == '' || pathname == '/index') {
res.end('歡迎來到首頁');
} else if(method = '/list') {
res.end('歡迎來到列表頁')
} else {
res.end('頁面不存在')
}
} else if(method = 'post') {
res.end('歡迎來到列表頁')
}
});
app.listen(3000);
console.log('伺服器啟動成功');
4.5靜態資源
伺服器不需要處理,可以直接響應給客戶端的資源就是靜態資源,例如CSS、JavaScript、image檔案。
const http = require('http');
const url = require('url');
const path = require('path');
const fs = require('fs');
const mine = require('mine');
const app = http.createServer();
app.on('request',(req,res) => {
let pathname = url.parse(req.url).pathname;
pathname = pathname == '/' ? '/default.html' : pathname;
let realPath = path.join(__dirname,'public' + pathname);
//獲得當前路徑的type值
let type = mine.getType(realPath);
fs.readFile(realPath, (error,result) => {
if(error != null) {
res.writeHead(404,{
'content-type':'text/html;charset=utf8'
})
res.end('讀取失敗');
return;
}
res.writeHead(404,{
'content-type':'type'
})
res.end(result)
});
});
app.listen(3000);
console.log('伺服器啟動成功');
4.6動態資源
相同的請求地址不同的響應資源,這種資源就是動態資源
http://www.itcast.cn/article?id=1
http://www.itcast.cn/article?id=2