当前位置: 首页 > 后端技术 > Node.js

Node.js实现一个HTTP服务器

时间:2023-04-03 20:23:27 Node.js

项目地址http服务器标题设计一个模拟HTTP服务器程序自己设计一个WEB程序,监听80端口,支持多客户端连接,可以满足客户的HTTP请求(浏览器访问),包括以下功能:1、基本功能:get、post(带数据请求)、head请求2、模拟登录访问,页面重定向功能(设计登录页面login.html,首页index.html,如果直接访问index.html,会跳转到登录页面,登录后只能打开首页)3.其他(如cookie)效果展示思路当用户打开127.0.0.1:8080这个URL时,客户端发起一个get请求,请求路径为/,服务器返回login.html页面。if(request.url==='/'){fs.readFile('./login.html',function(err,data){if(!err){response.writeHead(200,{"Content-Type":"text/html;charset=UTF-8"});response.end(data)}else{throwerr;}});}当用户试图通过浏览器地址访问/index时,服务器会判断requestheader是否携带cookies,如果不携带则将请求重定向到/。if(!request.headers.cookie){response.writeHead(301,{'Location':'/'})response.end()}如果有cookie,将浏览器重定向到index.html页面窗口。location.href='/index'用户在login.html界面输入用户名点击登录,客户端会携带用户名发起post请求letinput={name:document.querySelector('.input').value}letrequest=newXMLHttpRequest();//创建一个新的XMLHttpRequest对象request.open('POST','/login',true)request.send(JSON.stringify(input))服务器接收参数,设置cookieresponse.writeHead(200,{//cookie即可只能在当前域名和父域名上设置,同级域名无效'Set-Cookie':`name=${json.name}`,'Content-Type':'text/普通的',})响应。end()如果客户端发起HEAD请求,只返回对应的headerif(request.url==='/getHead'){response.writeHead(200);响应.end()}