login.html
<form action="http://localhost:3000/login" method="post">
用户名: <input type="text" name="username"/>
密码:<input type="password" name="password" />
<input type="button" value="提交" />
</form>
staticServer.js
const path = require('path');
const fs = require('fs');
const mime = require('./mime.json');
exports.staticServer = (req, res, root) =>{
fs.readFile(path.join(root, req.url),(err, fileContent) =>{
if(err){
res.writeHead(404, {
'Content-Type': 'text/plain;charset=utf8'
});
res.end('server error');
}else{
//根据不同的文件扩展名,设置不同的响应头
let dtype = 'text/html';
let ext = path.extname(req.url);
if(mime[ext]){
dtype = mime[ext];
}
//如果显示的是文本信息,那么设置编码
if(dtype.startsWith('text')){
dtype += ';charset=utf8';
}
res.writeHead(200,{
'Content-Type': dtype
});
res.end(fileContent);
}
});
}
main.js
//登录验证功能实现
const http = require('http');
const ss = require('./staticServer.js');
const querystring = require('querystring');
const url = require('url');
http.createServer((req, res) => {
//启动静态资源服务
if(req.url.startsWith('/www')){
ss.staticServer(req, res, __dirname);
}
//动态资源
if(req.url.startsWith('/login')){
//get请求
if(req.method == 'GET'){
let param = url.parse(req.url, true).query;
if(query.username == 'admin' && query.password == '123456'){
res.end('get success');
}else{
res.end('get failure');
}
}
//POST请求
if(req.method == 'POST'){
let pdata = '';
req.on('data', (chunk) => {
pdata += chunk;
});
req.on('end', ()=>{
let obj = querystring.parse(pdata);
if(obj.username == 'admin' && obj.password == '123'){
res.end('post success');
}else{
res.end('post failure');
}
});
}
}
}).listen(3000, ()=>{
console.log('running........');
});