html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button id="btn">获取数据</button>
<p id="cont"></p>
<script>
btn.οnclick=function(){
alert('点击了')
// 1.创建http请求对象
var xhr=new XMLHttpRequest()
// 2.打开服务器连接 请求的接口
xhr.open('get','http://127.0.0.1:3000/index',true)
// 3.添加事件 服务器有响应 自动触发函数
xhr.οnlοad=function(){
console.log(xhr.responseText);
cont.innerHTML=xhr.responseText
}
// 4.向服务器发送请求
xhr.send()
}
</script>
</body>
</html>
js文件
// 引入模块
const express=require('express')
// 引入模块 解决跨域
const cors=require('cors')
// 创建服务器
const app=express()
// 使用模块
app.use(cors())
// 设置端口
app.listen(3000,()=>{
console.log('启动成功');
})
// 托管静态资源
app.use(express.static('./public'))
app.use(express.urlencoded({
extended:true
}))
// 添加路由
app.get('/index',(req,res)=>{
res.send('这是首页')
})
app.post('/mylogin',(req,res)=>{
console.log(req.body);
res.send('登录成功')
})