项目地址
题目
设计一个模拟http服务端程序
自己设计一个web的程序,监听80端口。支持多客户端连接,能满足客户的http请求(浏览器访问),包括以下功能:
1.基本功能:get、post(带数据请求)、head请求
2.模拟登陆访问,页面redirector功能(设计登陆页面login.html、主页,如果直接访问则跳转到登陆页面,只有登陆后才能打开主页)
3.其他(如cookie)
效果展示
思路
用户打开网址 127.0.0.1:8080
时,客户端发起 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 { throw err; } }); }
当用户试图通过浏览器地址访问 /index
时,服务端会判断请求头是否携带 cookie ,若没有则将请求重定向到 /
。
if (!request.headers.cookie) { response.writehead(301, { 'location': '/' }) response.end() }
如果有携带 cookie ,则将浏览器重定向到 页面
window.location.href = '/index'
用户在 login.html 界面输入用户名并点击登录,客户端会携带用户名发起一个 post 请求
let input = { name: document.queryselector('.input').value } let request = new xmlhttprequest(); // 新建xmlhttprequest对象 request.open('post', '/login', true) request.send(json.stringify(input))
服务端接收参数,设置 cookie
let input = { name: document.queryselector('.input').value } let request = new xmlhttprequest(); // 新建xmlhttprequest对象 request.open('post', '/login', true) request.send(json.stringify(input))
如果客户端发情 head 请求,只返回相应头
if (request.url === '/gethead') { response.writehead(200); response.end() }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
使用npm命令提示: 'npm' 不是内部或外部命令,也不是可运行的程序的处理方法
Node Express用法详解【安装、使用、路由、中间件、模板引擎等】
Node Mongoose用法详解【Mongoose使用、Schema、对象、model文档等】
网友评论