http serverhtml
设计一个模拟HTTP服务端程序git
本身设计一个WEB的程序,监听80端口。支持多客户端链接,能知足客户的HTTP请求(浏览器访问),包括如下功能:github
1.基本功能:get、post(带数据请求)、head请求json
2.模拟登录访问,页面redirector功能(设计登录页面login.html、主页index.html,若是直接访问index.html则跳转到登录页面,只有登录后才能打开主页)浏览器
3.其余(如cookie)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() }
window.location.href = '/index'
let input = { name: document.querySelector('.input').value } let request = new XMLHttpRequest(); // 新建XMLHttpRequest对象 request.open('POST', '/login', true) request.send(JSON.stringify(input))
response.writeHead(200, { // cookie只能设置当前域名和父域名,同级域名无效 'Set-Cookie': `name=${json.name}`, 'Content-Type': 'text/plain', }) response.end()
if (request.url === '/getHead') { response.writeHead(200); response.end() }