服务器创建:
1.首先在powershell中输入 express init (引入express模块)
2.在pw中输入 npm install express 本地安装express模块 后面加 -g 可以全局安装
3.创建index.js 写入:var exprsee = require('express')
var app = express()
app.use(express.static('public'))
app.listen(5000,function(){
console.log('hello')
})
创建public文件 并且在文件中写入html文件 然后就可以运行了
接口搭建:
定义请求接口,后端的接口类似于js事件监听,当服务器听到客户端请求时会触发对应的接口,从而调用接口的回调函数
监听get方式的登录请求
app.get("/login", function(request, response){
// 回调中有两个参数: 请求对象和响应对象
// request 请求对象: 浏览器发送给服务器的数据对象 简写 req
// response 响应对象: 服务器返回给浏览器的数据对象 简写 res
// get请求的数据存放在query字段中
console.log(request.query)
// 服务器需要做出响应,客户端才会拿到结果
// response.send("恭喜你,登录成功")
})
// 监听post方式的登录请求
// post请求的数据在请求体中,需要一个解析器body-parser解析出来
var bodyParser = require("body-parser")
// 使用解析器解析post请求体数据, 解析到req.body字段中
app.use(bodyParser.urlencoded({extended: false}))
app.post("/login", function(req, res){
// post请求的数据是在请求体中, 会被解析到body字段中
console.log(req.body)
// 使用send函数响应字符串
// res.send("注册成功")
// 使用json函数响应对象
// res.json({
// msg: "恭喜你,登录成功"
// })
if(!req.body.username || !req.body.password ){
res.json({ msg: "账号或密码不能为空" })
return; // 响应后不会结束, 可使用return结束
}
// 读取userInfo目录下所有账号, 如果存在,再判断密码, 如果不存在,登录失败
fs.readdir("./public/userInfo", function(err, arr){
if(err){
res.json({msg: "系统错误,请重试"})
return;
}
var name = arr.find(item=>{
return item == req.body.username
})
if(name){
var path = "./public/userInfo/" + req.body.username
fs.readFile(path, function(err, data){
if(data == req.body.password){
res.json({msg: "登录成功"})
}else{
res.json({msg: "密码错误"})
}
})
}else{
res.json({msg: '用户不存在,登录失败'})
}
})
})
// 注册接口
app.post("/register", function(req,res){
console.log(req.body)
if(!req.body.username || !req.body.password ){
res.json({ msg: "账号或密码不能为空" })
return; // 响应后不会结束, 可使用return结束
}
// Cannot set headers after they are sent to the client, 重复响应
// res.json({name:123})
// 读取userInfo目录下所有账号,如果存在,就注册失败, 没有账号就注册成功
fs.readdir("./public/userInfo", function(err, arr){
var result = arr.some(item=>{
return item == req.body.username
})
if(result){
res.json({ msg : "用户名已存在, 注册失败"})
}else{
var path = "./public/userInfo/"+req.body.username;
fs.writeFile(path, req.body.password, ()=>{});
res.json({ msg : "注册成功"});
}
})
})
// 注意: 服务器代码修改之后,需要重启服务器才能生效