项目地址
http服务器
科目
设计一个模拟HTTP服务器的程序
设计一个监控80端口的网络程序。支持多客户端连接,可以满足客户的HTTP请求(浏览器访问),包括以下功能:
1.基本功能:获取、发布(带数据请求)和标题请求
2.模拟登录访问,页面重定向器功能(设计登录页面login.html,首页index.html,如果直接访问index.html,跳转到登录页面,登录后只打开首页)
3.其他(如cookie)
效果显示
思路
当用户打开URL 127.0.0.1:8080时,客户端发起get请求,请求路径为/,服务器返回login.html页面。
if(request . URL==='/'){ fs . readfile('。/login.html ',函数(err,data) { if(!err) { response.writeHead(200,{ ' Content-Type ' : ' text/html;charset=UTF-8 ' });response . end(data)} else { throw err;} });}当用户尝试通过浏览器地址访问/索引时,服务器会判断请求头是否携带cookie,如果没有,则将请求重定向到/。
if(!request . headers . cookie){ response . write head(301,{ ' location ' : '/})response . end()}如果有cookie,请将浏览器重定向到index.html页面
Window.location.href='/index '当用户在login.html界面输入用户名并点击登录时,客户端将使用该用户名发起一个post请求。
让input={ name : document . queryselector . '。输入')。value}let请求=new XMlhttprequest();//创建一个新的XMLHttpRequest对象request.open ('post ','/login ',true)request . send(JSON . stringfy(input))。服务器接收参数并设置cookie
让input={ name : document . queryselector . '。输入')。value}let请求=new XMlhttprequest();//新建一个XMLHttpRequest对象request.open ('post ','/login ',true)request . send(JSON . stringfy(input))如果客户端请求发情期head,将只返回对应的HEAD
if(request . URL==='/getHead '){ response . write head(200);Response.end()}以上就是本文的全部内容。希望对大家的学习有帮助,支持我们。