<!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script> <title>Document</title> </head>
<body> <button>GET</button> <button>POST</button> <button>AJAX</button> </body> <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', { //usr 参数 params: { id: 100, vip: 7 }, //请求头信息 headers: { name: 'DX3', age: 20 } }).then(response => { console.log(response); }) }
btns[1].onclick = function () { //post请求,第一个参数是url,第二个参数是请求体,第三个参数是其它 axios.post('/axios-server', { username: 'admin', pwssword: 'admin' }, { //usr 参数 params: { id: 100, vip: 7 }, //请求头信息 headers: { height: 'DX3', weight: 20 } }) }
btns[2].onclick = function () { axios({ method: 'post', url: '/axios-server', params: { vip: 10, level: 30 }, headers: { a: 10, b: 20 }, data: { username: 'admin', password: 'admin' } }).then(response => { console.log(response); //响应状态码 console.log(response.status); //响应状态字符串 console.log(response.status.Text); //响应头信息 console.log(response.headers); //响应体 console.log(response.data); }) }
</script>
</html> ===========server.js=========== //引用 express const { request, response, json } = require('express'); const express = require('express');
//创建应用对象 const app = express();
//创建路由规则, // request 是对请求报文的封装 // response 是对响应报文的封装 //app.all 可以接收任意类型的请求头
app.all('/axios-server', (request, response) => { //设置响应头,设置充许跨域 response.setHeader('Access-Control-Allow-Origin', '*'); response.setHeader('Access-Control-Allow-Headers', '*'); const data = { name: 'xiaoming', age: '18' }; //setTimeout(() => { response.send(JSON.stringify(data)); //}, 3000);
})
// 监听端口启动服务 app.listen(8000, () => { console.log('服务已经启动,8000端口监听中.......'); })