伺服器端基本概念02

1.POST請求參數

  • 參數被放置在請求體重進行傳輸;
  • 獲取POST參數需要使用data事件和end事件;
  • 使用querystring系統模組將參數轉換為對象格式。
  • 布置伺服器獲取參數
  1. html

 

 

 

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="//localhost:3000" method="post">
<input type="text" name="usname">
<input type="password" name="pwd">
<input type="submit">
</form>

</body>
</html>

  2.app.js

 

const http = require('http');
const app = http.createServer();
//導入系統模組querystring用戶將HTTP參數轉換為對象格式
const querystring = require('querystring')
app.on('request',(req,res)=>{
res.writeHead(200,{
'content-type':'text/html;charset=utf8'
})
//監聽參數傳輸事件
let postData = '';
req.on('data',params=>{
postData += params;
})
//監聽參數傳輸完畢事件
req.on('end',()=>{
console.log(querystring.parse(postData));
    })
res.end('提交成功')
})
app.listen(3000);
console.log('伺服器部署成功')

 

   3.獲取列印輸入值

 

 

 

 

2.路由

  • 路由是值客戶端請求地址與伺服器端程式程式碼的對應關係。簡單的說,就是請求什麼返回什麼。
const http = require('http');
const app = http.createServer();
const url = require('url');
app.on('request',(req,res)=>{
res.writeHead(200,{
'content-type':'text/html;charset=utf8'
})
const method = req.method.toLowerCase(); //將方法大寫轉換為小寫
const pathname = url.parse(req.url).pathname; //解析出客戶端輸入的地址
if(method ==='get'){
if(pathname == '/'||pathname == '/index'){
res.end('歡迎來到首頁')
}else if(pathname=='/777'){
res.end('歡迎來到777')
}else {
res.end('抱歉,您所訪問的頁面不存在')
}
}else if(method === 'post'){
if(pathname == '/'||pathname == '/index'){
res.end('歡迎來到首頁1')
}else if(pathname=='/777'){
res.end('歡迎來到7771')
}else {
res.end('抱歉,您所訪問的頁面不存在1')
}
}
})
app.listen(3000);
console.log('伺服器部署成功')

 

 

 

3.靜態資源

  •  伺服器不需要處理,可以直接響應給客戶端的資源就是靜態資源,例如css,JavaScript,image文件等。
  • 為什麼沒有書寫res.writeHead(202,{…})程式碼,獲取到的頁面能正常顯示漢字,不出現亂碼?
  • 因為在獲取到的html文件中,已經書寫utf-8文件編碼格式,所以能正常顯示。
  •  

     

     

 

 

 

const http = require('http');
const app = http.createServer();
const url = require('url');
const path = require('path');
const fs = require('fs');
app.on('request',(req,res)=>{
/* res.writeHead(404,{
'content-type':'text/html;charset=utf8' //如果放在外面,則此頁面所有返回404,無法顯示樣式
})*/
let pathname = url.parse(req.url).pathname;
let realPath = path.join(__dirname,'public'+pathname);
fs.readFile(realPath,(error,result)=>{
if(error != null){
res.writeHead(200,{
'content-type':'text/html;charset=utf8'
})
res.end('文件獲取失敗');
return;
}
res.end(result);
})

})
app.listen(3000);
console.log('超級伺服器已部署')

 

  • 錯誤反思與解決:
    • 頁面獲取後,沒有css樣式與js效果:
    •  

       

    • 原因:把要返回的錯誤文件格式放在全局中,導致返回的頁面無法調用css,JavaScript。
    • 解決辦法:把讀取頁面失敗要返回的編碼格式放在對應文件中。問題解決成功!頁面成功引用css,JavaScript。
    •  

       

       

       

 

Tags: