1、启动服务
// 引入express
const express=require('express');
// 创建应用对象
const app=express()
// 创建路由规则
// request是对请求报文的封装
// response对响应报文的封装
app.get('/server',(request,response)=>{
// 设置响应头,设置允许跨域
response.setHeader("Access-Control-Allow-Origin", "*")
// 设置响应体
response.send('啦啦啦啦啦啦get')
})
// 创建路由规则 all可以接收任意类型的请求
app.all('/index',(request,response)=>{
// 设置响应头,设置允许跨域
response.setHeader("Access-Control-Allow-Origin", "*")
// 响应头,所有类型的头信息都可以接收
response.setHeader("Access-Control-Allow-Headers", "*")
let obj={
name:'小明',
age:18
}
let data=JSON.stringify(obj)
// 3秒之后响应
setTimeout(() => {
// 设置响应体
response.send(data)
}, 3000);
})
// 监听端口启动服务
app.listen(8000,()=>{
console.log('服务器已启动。。。。。');
})
2、取消请求,请求超时,网络异常操作
<body>
<button>点击请求</button>
<div id="box"></div>
<script>
const btn=document.querySelectorAll('button')
const box=document.getElementById('box')
let xhr=null
let isSending=false //是否正在发送ajax请求
btn[0].addEventListener('click',function(){
// 如果正在发送请求,则取消发送,如果没有,则发送ajax请求
if(isSending){
xhr.abort()
}
// 创建对象
xhr=new XMLHttpRequest()
// 正在发送ajax请求
isSending=true
// 设置响应数据类型
xhr.responseType='json'
// 设置超时时间
xhr.timeout=4000
// 初始化
xhr.open('POST','http://192.168.1.6:8000/index')
// 发送
xhr.send()
// 如果请求超过设定的时间,则触发此函数
xhr.ontimeout=function(){
alert('请求超时')
}
// 没网时触发此函数
xhr.onerror=function(){
alert('网络出小差了。。。')
}
// 事件处理函数,处理服务端返回的结果
xhr.onreadystatechange=function(){
// readystate是xhr的属性,表示0 1 2 3 4
// 0表示没状态,1表示初始化,2发送,3返回部分结果,4返回全部结果
if(xhr.readyState===4){
// 数据全部返回时请求结束
isSending=false
// 状态码为200到300之间的返回正常
if(xhr.status>=200&&xhr.status<300){
console.log(xhr.response);
box.innerHTML=xhr.response.name
}
}
}
})
</script>
</body>