赞
踩
客户端:
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Axios 发送 Ajax 请求</title>
- <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
- </head>
-
- <body>
- <h2>Axios 发送三种请求</h2>
- <button>GET</button>
- <button>POST</button>
- <button>通用方法Ajax</button>
-
- <script>
- const btns = document.querySelectorAll('button');
-
- //配置baseurl 对路径简化
- axios.defaults.baseURL = 'http://127.0.0.1:8000';
-
- btns[0].onclick = function () {
- console.log("test");
- //get 请求
- axios.get('/axios-server', {
- //和jQuery不一样
- //url参数
- params: {
- id: 100,
- vip: 10
- },
- //请求头信息
- headers: {
- name: "axio111",
- age: 18
- }
- }).then(value => {
- //这个响应是基于promise的
- console.log(value);
- });
- };
-
- btns[1].onclick = function () {
- console.log("test");
- //post 请求
- axios.post('/axios-server', {
- username: "admin",
- password: 123
- }, {
- //和jQuery不一样
- //url参数 行 头 体
- params: {
- id: 100,
- vip: 10
- },
- //请求头信息
- headers: {
- height: 172,
- weight: 130
- },
-
- });
- };
-
- //很清晰
- btns[2].onclick = function () {
- axios({
- //请求方法
- method: 'POST',
- //参数1 url
- url: '/axios-server',
- //2url 参数
- params: {
- vip: 10,
- level: 80
- },
- //3头信息参数
- headers: {
- a: 100,
- b: 200
- },
- //4请求体参数
- data: {
- username: "admin",
- password: 123
- }
- //。then 响应结果
- }).then(response => {
- console.log(response);
- })
- };
- </script>
-
- </body>
-
- </html>

服务端:
- //Axios 服务
- app.all('/axios-server',(request,response)=>{
-
- //设置响应头 ('Access-Control-Allow-Origin','*');作用:允许跨域
- response.setHeader('Access-Control-Allow-Origin','*');
-
- response.setHeader('Access-Control-Allow-Headers','*');
-
- const data={name:'zhangsan',age:18,sex:'man'}
- response.send(JSON.stringify(data));
-
-
- });
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。