<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Node实现登陆页面</title> <link rel="stylesheet" href="css/bootstrap.css"> </head> <body> <h1 class="text-center">实现验证登陆</h1> <div class="container"> <form method="get" action="http://localhost:3000/login.html"> <div class="form-group"> <label for="user1">用户</label> <input type="text" class="form-control" id="user1" placeholder="输入用户" name="username" required> </div> <div class="form-group"> <label for="password1">密码</label> <input type="password" class="form-control" id="password1" placeholder="输入密码" name="pwd" required> </div> <button type="submit" class="btn btn-primary btn-block">登陆</button> </form> </div> </body> </html>
const http = require('http') const fs = require('fs') const path = require('path') let server = http.createServer((req,res)=>{ // console.log(req.url.startsWith('/login')) // true(login) false(bootstrap) false(bootstrap) fs.readFile(path.join(__dirname,'/source',req.url),'utf8',(err,data)=>{ // 2.1 判断文件是否存在,不存在返回404 // 2.2 最好使用req.url(这样.css文件发送请求,req.url也能获取到。才会连接.css) if(err){ res.writeHead('404',{ 'Content-Type':'text/plain;charset=utf8' }) res.end('页面不存在了') }else{ res.end(data) } }) }).listen(3000,()=>{ console.log('The Server Running...') })
const http = require('http') const fs = require('fs') const path = require('path') const {URL} = require('url') let server = http.createServer((req,res)=>{ let myURL = new URL(path.join(__dirname,req.url)) if(myURL.searchParams.get('username')){ let user = myURL.searchParams.get('username') let pwd = myURL.searchParams.get('pwd') res.writeHead('200',{ 'Content-Type':'text/plain;charset=utf8' }) res.end('你好,'+user) } fs.readFile(path.join(__dirname,'/source',req.url),'utf8',(err,data)=>{ if(err){ res.writeHead('404',{ 'Content-Type':'text/plain;charset=utf8' }) res.end('页面不存在了') }else{ res.end(data) } }) }).listen(3000,()=>{ console.log('The Server Running...') })
// 1.构建web服务器
// 2.渲染页面
// 2.1 判断页面是否存在
// 2.2 不是的话返回404
// 2.3 是的话,读取文件并渲染到页面上
// 3.登陆后获取用户名和密码
// 3.1 点击登陆按钮会从新发送请求
// 3.2 此时能拿到用户名和密码,但要处理下
// 3.1 获取url地址的searchParams的用户名和密码
// 4. 实现登陆
// 4.1 返回新页面css