Axios发送Ajax请求
axios.html
- get
- post
- 通用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>axios发送ajax请求</title>
<script crossorgin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.js"></script>
</head>
<body>
<!-- 210323 -->
<button>GET</button>
<button>POST</button>
<button>AJAX</button>
<script>
const btn = document.querySelectorAll('button');
//配置baseURL
axios.defaults.baseURL = 'http://127.0.0.1:8000';
btn[0].onclick = function () {
//GET 请求
axios.get('/axios-server', {
//url
params: {
id: 100,
vip: 7
},
//请求头信息
headers: {
name: '123',
age: 20
}
}).then(value => {
console.log(value);
});
}
btn[1].onclick = function () {
//参数1:url,参数2:请求体,参数3:其他配置
axios.post('/axios-server', {
username: 'admin',
password: '123'
}, {
//url
params: {
id: 200,
vip: 9
},
headers: {
height: 180,
weight: 150
}
})
}
//通用方式
btn[2].onclick = function () {
axios({
//请求方法
method: 'POST',
//url
url: 'axios-server',
//url参数
params: {
vip: 10,
level: 30
},
//头信息
headers: {
a: 100,
b: 100
},
//请求体参数
data: {
username: 'phy',
password: 234
}
}).then(response => {
console.log(response);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.data);
})//then处理
}
</script>
</body>
</html>
server.js
//axios服务
app.all('/axios-server', (request, response) => {
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Headers', '*')
//设置响应体
// response.send('Hello Axios Ajax');
const data = {
name: 'phy'
};
response.send(JSON.stringify(data));
});