nodejs抓取动态网页(构建服务器Node.js一些模块的学习方法-上海怡健医学)
优采云 发布时间: 2021-09-15 13:13nodejs抓取动态网页(构建服务器Node.js一些模块的学习方法-上海怡健医学)
为了回顾node.js的一些模块的学习,我们首先编写了一个静态页面。为了追求效率和美观,我们使用bootstrap的bootstrap.css身份验证登录功能。我们只需设置用户名、密码和登录函数结构
代码
Node实现登录页面
实现验证登录
用户
密码
登录
使用node.js构建服务器,使用HTTP模块创建服务器,使用FS和path模块查看我们的静态页面,注意表单的动作、端口和请求路径与后台部分的代码一致
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...')
})
本地服务器查看页面效果并测试是否加载了静态资源
测试各功能,解析node.js,实现认证登录功能,导入URL模块,点击登录时获取用户名和密码
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.buildweb服务器
//2.render页面
//2.1确定页面是否存在
//2.2如果不是,返回404
//2.3如果是,请读取文件并将其呈现到页面
//3.登录后获取用户名和密码
//3.1单击登录按钮将重新发送请求
//3.2此时,您可以获得用户名和密码,但您必须处理它
//3.1获取URL地址的searchparams的用户名和密码
//4.登录
//4.1返回新页面