1.POST请求参数
1)html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://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.静态资源
const http = require(‘http‘);
const app = http.createServer();
const url = require(‘url‘);
const path = require(‘path‘);
const fs = require(‘fs‘);
const mime = require(‘mime‘)
app.on(‘request‘,(req,res)=>{
/* res.writeHead(404,{
‘content-type‘:‘text/html;charset=utf8‘ //如果放在外面,则此页面所有返回404,无法显示样式
})*/
let pathname = url.parse(req.url).pathname;
pathname = pathname == ‘/‘?‘/index.html‘:pathname;
let realPath = path.join(__dirname,‘public‘+pathname);
const type = mime.getType(pathname); //获取文件实时传输类型
fs.readFile(realPath,(error,result)=>{
if(error != null){
res.writeHead(404,{
‘content-type‘:‘text/html;charset=utf8‘
})
res.end(‘文件获取失败‘);
return;
}
res.writeHead(200,{
‘content-type‘: type
})
res.end(result);
})
})
app.listen(3000);
console.log(‘超级服务器已部署‘)
原文:https://www.cnblogs.com/kmfc7/p/12852921.html