How to use get, post, and general ajax method requests in the axios framework.

Back to Article List
This article describes how content is used inside the framework axios get, post, 通用ajax方法request.
Axios is currently the most popular tool library in the front-end Ajax. It is the ajax toolkit officially recommended by vue and react.
Functions:
1. You can send requests in node.js
2. Support Promise API (es6's new asynchronous programming solution)
3. Interceptor mechanism
4. Data conversion
5. Request cancellation
6. Automatic conversion to json
7. Security related protection

In the final analysis, it is still used to send ajax requests

We don’t install it in npm, and use the cdn link directly (put the link directly in htnl)
1. Uncompressed, you can easily understand the version

<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.js"></script>

2. Compressed version

<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.min.js"></script>

GET request 1 routing 2 other settings
axios.get(url[, config])
POST request 1 routing 2 parameters (request body) 3 other settings
axios.post(url[, data[, config]])

注意一
The request body of the post request method will be converted and passed in the json format string
Insert picture description here

详细解释在案例代码里面

Case code

Insert picture description here

1. Create in testseleven文件夹and in this folder
2. Create simpel.html文件
3. Createserver.js文件

simpel.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 存放Axios链接  -->
    <!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script> -->
    <!-- 添加允许跨源属性获取链接  向该链接发送请求的时候不会发送当前域名下的cookies  一般当前域名的cookies存放着你的帐号密码-->
        <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.js"></script>
    <title>Axios发送ajax请求</title>
</head>
<body>
    <button style="background-color: tomato;">GET</button>
    <button style="background-color: tomato;">POST</button>
    <button style="background-color: violet;">通用Ajax</button>
    <div id="result" style="width: 180px;height: 100px;border: solid 2px teal;"></div>
    <script>
        // 把所有的按钮标签都选择
        const btns = document.querySelectorAll('button');
        // 配置 baseURL
        axios.defaults.baseURL = 'http://127.0.0.1:8000';
        // 第一个按钮
        btns[0].onclick = function(){
     
     
            // GET请求
            axios.get('/axiosget', {
     
     
                // url 参数
                params: {
     
     
                    id: 100,
                    name: 999
                },
                // 请求头信息
                headers:{
     
     
                    sex: 'boy',
                    age: 999
                }
                // axios数据返回和处理和jquery不一样,
                // jquery使用的是回调函数
                // axios使用的是基于Promise   .then(value => {};) 箭头函数
            }).then(value =>{
     
     
                console.log(value);
            })
        }
        // 第二个按钮
        btns[1].onclick = function(){
     
     
            // POST请求   axios.post('1.路由',{2.参数-请求体},{3.其他设置})
            // 2.参数-请求体  将会被转换未json格式字符串传递过去
            axios.post('/axiospost',{
     
     
                username:'dayo',
                password:'dayo'
            },{
     
     
                // url参数
                params: {
     
     
                    id: 999,
                    vip: 999
                },
                // 请求头参数
                headers:{
     
     
                    height:999,
                    weight:999
                }
                // 打印返回来的数据
            }).then(value =>{
     
     console.log(value);})
        }
        // 第三个按钮
        btns[2].onclick =function(){
     
     
            axios({
     
     
                // 请求方法
                method: 'POST',
                // url
                url: '/axios-server',
                // url参数
                params: {
     
     
                    vip: 999,
                    level: 999
                },
                // 请求头信息
                headers: {
     
     
                    a: 999,
                    b: 999
                },
                // 请求体信息
                data: {
     
     
                    username: 'dayo',
                    password: 'dayo'
                }
                // 打印响应的所有信息
            }).then(response=>{
     
     console.log(response);
            // 另外打印响应状态码
            console.log(response.status);
            // 响应状态字符串
            console.log(response.statusText);
            // 响应头信息
            console.log(response.headers);
            // 响应体 
            console.log('响应体:',response.data);
            })
        }
    </script>
</body>

</html>

server.js文件

// 1. 引入express
const express = require('express');

// 2.创建对象
const app = express();
// 3.创建路由规则  里面的形参 request与response   (自己可以随便定义名字的)
//  建议写成  request与response  因为可以见名思意,方便自己看
// request  对请求报文的封装
// responst 对响应报文的封装
//  请求路径为'/server'

// 当使用post请求时候会因为发送的信息没有收到对应的结果所以回报错
// 所以该处使用all  表示可以接收任意类型的请求      如get post 等等


// 一:get请求
app.all('/axiosget', (request, response)=>{
    
    
    response.setHeader('Access-Control-Allow-Origin','*');
    response.setHeader('Access-Control-Allow-Headers','*');
    response.send('get请求成功,服务端非json数据返回,返回的是字符串格式.');
});
// 二 :post请求json数据
app.all('/axiospost', (request, response)=>{
    
    
    // 设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
    // 响应头        *号表示所有的头信息都可以接收
    response.setHeader('Access-Control-Allow-Headers','*');
    // 响应一个数据   把这个对象返回给浏览器
    const data = {
    
    
        name: 'post请求,服务端设置了json格式返回 '
    };
    // 对对象进行字符串转换
    let str = JSON.stringify(data);
    setTimeout(()=>{
    
    response.send(str);},200);
});
// 三:axios通用ajax请求 json数据
app.all('/axios-server', (request, response)=>{
    
    
    response.setHeader('Access-Control-Allow-Origin','*');
    response.setHeader('Access-Control-Allow-Headers','*');
    const data = {
    
    
        name: 'axios通用ajax请求的post请求方法,服务端设置了json格式返回'
    };
    let str = JSON.stringify(data);
    setTimeout(()=>{
    
    response.send(str);},200);
});



// 4. 监听端口启动服务
// 这里listen(8000)后面添加了一个回调,用来提示,告诉自己是否监听成功
app.listen(8000, ()=>{
    
    
    console.log("服务已经启动,8000端口监听中......");
});

Guess you like

Origin blog.csdn.net/weixin_47021806/article/details/112200728