示例代码
express代码
const express = require('express')
const app = express()
const cors = require('cors')
app.use(cors())
app.get('/list', (req, res) => {
console.log('接收到的参数是', req.query)
setTimeout(() => {
res.send({ message: 'success', code: 2000, data: [{ name: '张三', age: 18 }] })
}, 4000)
})
app.post('/data', (req, res) => {
setTimeout(() => {
res.send({ message: 'success', code: 2000, data: [{ name: '张三666', age: 18 }] })
}, 4000)
})
app.listen('3000', () => {
console.log('服务启动成功')
})
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button onclick="sendGet()">get请求</button>
<button onclick="sendPost()">post请求</button>
<button onclick="cancel()">取消</button>
</body>
<script>
let controller = null
if (!controller) {
function sendGet() {
controller = new AbortController()
fetch('http://localhost:3000/list?name=haha&age=19', {
signal: controller.signal
})
.then((res) => {
if (res.ok) {
return res.json()
}
})
.catch((err) => {
console.log(err)
})
}
function sendPost() {
controller = new AbortController()
fetch('http://localhost:3000/data', {
method: 'POST',
body: JSON.stringify(),
headers: {
'Content-Type': 'application/json'
},
signal: controller.signal
}).then((res) => {
console.log(res)
})
}
}
function cancel() {
controller.abort()
controller = ''
}
</script>
</html>