当服务器端口被占用时使用如下指令
//netstat -ano|findstr "3000”
//taskkill -PID xxxxx -F
get请求发送参数的第二种方式
// /hello/:id 表示当前用户访问 /hello/xxx 时就会触发
//在路径中已冒号命名的部分称为param,在get请求它可以被解析为请求参数
//req.query以对象形式传参 params按照类似数据方式传参
//params一般不会传递特别复杂的参数
app.get("/hello/:name/:age/:gender",(req,res) => {
//约定优于配置
//可以通过req.param属性来获取这些参数
console.log(req.params);
res.send("hello")
})
get传输参数的方式安全性较低,因此较常使用post请求,利用请求体提高安全性,同时不限制参数的大小。默认情况下 express不会自动解析请求体,需要通过中间件来为其添加功能。通过req.body来获取post请求的参数(请求体的参数)。
//引入解析请求体的中间件以使用req.body
app.use(express.urlencoded())
app.post("/login", (req,res) => {
// console.log(req.body);
const username = req.body.username
const password = req.body.password
if(username === "admin" && password === "123"){
res.send("登录成功")
}else{
res.send("xxx")
}
// res.send("<h1>post请求已收到</h1>")
})
//从登录页面获取信息
app.post("/login", (req,res) => {
const username = req.body.username
const password = req.body.password
//方法1.遍历数组 验证用户密码是否正确
//获取到用户的信息后需要根据用户名去用户数组中查找用户
// for(const user of USERS){
// if(user.username === username){
// //用户存在 检查密码
// if(user.password === password){
// res.send(`<h1>登陆成功 ${user.nickname}</h1>`)
// return
// }
// }
// }
// res.send("<h1>用户名或密码错误</h1>")
//方法2.find方法
const loginUser = USERS.find((item) => {
return item.username === username && item.password === password
})
if(loginUser){
res.send(`<h1>登陆成功 ${loginUser.nickname}</h1>`)
}else{
res.send("<h1>用户名或密码错误</h1>")
}
})
//用户注册
app.post("/register", (req,res) => {
//获取用户输入的数据
// console.log(req.body);
const {username,password,repwd,nickname} = req.body
const user = USERS.find(item =>{
return item/username === username || item.nickname === nickname
})
// console.log(user);
if(!user){
//进入判断说明用户不存在,可以注册
USERS.push({
username,
password,
nickname
})
res.send("<h1>注册成功</h1>")
}else{
res.send("<h1>用户名已存在</h1>")
}
})