使用axios发送ajax请求小示例(axios基于promise)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.min.js"></script>
</head>
<body>
<h1>axios发送ajax请求示例</h1>
<button>get请求</button>
<button>post请求</button>
<button>通用请求</button>
<script>
const btns = document.querySelectorAll('button');
//配置baseURL
axios.defaults.baseURL = 'http://127.0.0.1:8000';
btns[0].onclick = function(){
//get请求
axios.get('/axios-server',{
//参数
params:{
a:1,
b:2
},
//请求头信息
headers:{
name:'uncleTip',
age:40
}
//get请求无法对请求体进行设置
}).then(response => {
console.log(response);
});
}
btns[1].onclick = function(){
//post请求
axios.post('/axios-server',{//请求体data
name:'uncleTip',
age:40
},{
//参数
params:{
a:1,
b:2
},
//请求头信息(参数)
headers:{
height:185,
weight:50
}
}).then(response => {
//console.log(response);
});
}
btns[2].onclick = function(){
axios({
//method
method:'post',
//url
url:'/axios-server',
//参数
params:{
vip:10,
level:20
},
//头信息
headers:{
a:1,
b:2
},
//请求体
data:{
username:'uncleTip',
password:'123'
}
}).then(response => {
console.log(response);
console.log(response.status);//响应状态码
console.log(response.statusText);//响应状态字符串
console.log(response.headers);//响应头信息
console.log(response.data);//响应体
})
}
</script>
</body>
</html>
脚本:
const express = require('express');
const app = express();
app.all('/axios-server',(request,response)=>{
//允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
//允许自定义header头部信息
response.setHeader('Access-Control-Allow-Headers','*');
//设置响应
//response.send('hello axios ajax');
const data = {
name:'tom',
age:20
}
response.send(JSON.stringify(data));
})
app.listen(8000,()=>{
console.log('服务器已开启...')
})