服务器端基本概念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: