通过express创建服务器,监听9000端口,模拟服务端server.js代码如下:
const express = require("express") //引入模块
const app = express();
app.post("/login",(request,response)=>{
response.setHeader("content-type","text/html;charset=utf-8")
response.setHeader("access-control-allow-origin","*") //解决跨域问题
setTimeout(() => {
response.end("登录页面")
}, 3000);
})
app.get("/getserver",(request,response)=>{
console.log(request.httpVersion);//http版本
console.log(request.method);//接口方法
response.setHeader("content-type","text/html;charset=utf-8");//解决响应内容汉字乱码问题
response.end("getserver页面")
})
app.all("/home",(request,response)=>{
response.setHeader("access-control-allow-origin","*")
let data = {
name:"zhan",
age:18
}
//实现延迟效果
setTimeout(function(){
response.end(JSON.stringify(data))
},3000)
})
//监听端口
app.listen(9000,()=>{
console.log("server watch~~~")
})
服务器代码可以使用 node ./server.js 执行 或者 nodemon ./server.js
建议使用nodemon ,可以实现实时刷新,不用修改server.js后重新启动
客户端代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#result {
width: 150px;
height: 70px;
border:1px solid saddlebrown;
}
</style>
</head>
<body>
<button>点击将返回数据展示</button>
<button>取消请求</button>
<button>点击实现延时取消操作</button>
<button>防止恶意多次请求</button>
<div id="result"></div>
<script>
let result = document.getElementById("result");
let btnS = document.getElementsByTagName("button")
const xhr = new XMLHttpRequest();
//点击将返回数据展示
btnS[0].addEventListener("click",()=>{
xhr.open("post","http://127.0.0.1:9000/login");
xhr.send();
xhr.onreadystatechange = ()=>{
if(xhr.readyState == 4){
if(xhr.status >= 200 && xhr.status <300){
result.innerText = xhr.response
}
}
}
})
//取消请求
btnS[1].onclick = function(){
xhr.abort();//取消请求
}
//点击实现延时取消操作
btnS[2].onclick = function(){
xhr.open("post","http://127.0.0.1:9000/home");
xhr.timeout = 2000;//设置超时时限
xhr.ontimeout = function(){
//超时后的操作
console.log("请求已超时~")
}
xhr.send()
xhr.onreadystatechange =function(){
if(xhr.status >= 200 && xhr.status <300){
result.innerText = xhr.response
}
}
}
//防止恶意多次请求
let ope = false;
btnS[3].onclick = function(){
if(ope) xhr.abort(); //如果已经发送了请求,再次点击则取消上次请求
xhr.open("post","http://127.0.0.1:9000/home");
xhr.send()
ope = true
xhr.onreadystatechange =function(){
if(xhr.status >= 200 && xhr.status <300){
result.innerText = JSON.parse(xhr.response).name
}
}
}
</script>
</body>
</html>
文章展示了如何使用Express框架在Node.js中创建一个服务器,监听9000端口,处理POST和GET请求,包括设置响应头以解决跨域问题和延迟响应。客户端代码使用XMLHttpRequest对象进行交互,支持请求的发送、取消、超时以及防止恶意多次请求的功能。
1421

被折叠的 条评论
为什么被折叠?



