目录
node常用的开发框架
编写采用路由模式,每一个模式对应一个路由
①express启动服务,启动,挂载,托管
下载express 模块
cpnm i express
//插入express模块
const express=require("express")
//启动服务
const app=express()
//express中 静态资源托管
app.use(express.static("./public")) //该文件目录下的所有内容都可以链接至接口
//端口挂载
app.listen(8088,()=>{
console.log("服务器启动成功")
})
②express get请求
app.get("/login",(req,res)=>{
let query =req.query //get请求携带的参数 req.query
console.log(query)
res.send({message:"接收成功"}) //返回前端的内容
})
③express post 请求
express中解析post参数 需要引入body-parser模块 (内部模块不需要下载)
const bodyparser = requier("body-parser")
//全局应用 bodyparser模块
//express 官网查找文档
app.use(bodyparser.urlencoded{ //全局解析,固定写法,让express能够解析post请求
extended:false
})
app.post("/req",(req,res)=>{
//使用bodyparser后
let query=req.body //直接将post参数 放入req.body中
res.send({message:"接收成功"})
})
④验证码案例
前端编码
<p>
验证码:<input type="text" id="cap"> <img src="http://localhost:8088/getcaptcha" alt="">
</p>
<script>
$(function(){
//点击图片切换验证码
$("img").click(function(){
//网页为了节约资源,如果src中内容没有发生过变化时,不重复提交请求
//get请求 可以拼接任意参数
$(this).attr("src","http://localhost:8088/getcaptcha?"+Math.radom()) //拼接任意字符
})
//鼠标移除判断
$("#cap").blur(function(){
$.ajax(){
type:"get",
url:"http://localhost:8088/checkcaptcha",
data:{
text:$(this).val()
},
dataType:"json"
success(res){
soncole.log(res)
}
}
})
})
</script>
后端编码
//引入验证码模块
const svg = require("svg-captcha")
let Text=""
//获取验证码图片接口
app.get("/getcaptcha",(req,res)=>{
let captcha=svg.create({})
Text=captcha.text; //保存文字内容
res.type("svg") //设置返回内容是图片
res.send(captcha.data) //发送图片
})
//校验验证码
app.get("/checkcpatcha",(req,res)=>{
//发送text,跟后端产生的验证码内容进行比较
let{text}=req.query
if(text.toUppercase()==Text.toUppercase(){
//if(req.session){
res.send({message:"验证码正确"})
}else{
res.send({message:"验证码错误"})
}
})
})