axios基础入门

axios 是什么?

  1. 前端最流行的 ajax 请求库
  2. react/vue 官方都推荐使用 axios 发 ajax 请求
  3. 文档: https://github.com/axios/axios

axios 特点

  1. 基于 xhr + promise 的异步 ajax 请求库
  2. 浏览器端/node 端都可以使用
  3. 支持请求/响应拦截器
  4. 支持请求取消
  5. 请求/响应数据转换
  6. 批量发送多个请求

json-server

JSON-Server 是一个 Node 模块,运行 Express 服务器,你可以指定一个 json 文件作为 api 的数据源。如果没有写后台返回数据可以用这个来模拟后台返回的数据

安装

npm install -g json-server

在当前文件下建立db.json

{
    
    
  "persons":[
    {
    
    "id":1,"name":"zhangsan","age":18},
    {
    
    "id":2,"name":"lisi","age":19}
  ],
  "dogs":[
    {
    
    "id":1,"name":"xiaohei","age":4},
    {
    
    "id":2,"name":"xiaohuang","age":2}
  ],
  "school":{
    
    "name":"wsyu"}
}

启动 json-server

json-server可以直接把一个json文件托管成一个具备全RESTful风格的API,并支持跨域、jsonp、路由订制、数据快照保存等功能的 web 服务器

json-server --watch db.json

结果

输出一下内容即成功

\{
    
    ^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3000/persons
  http://localhost:3000/dogs
  http://localhost:3000/school

  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database
  Watching...

在这里插入图片描述

get请求

注意axios发送get请求要带参数时,携带的应该是params而不是data

<body>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <div class="container">
        <button>发送GET请求</button>
        <button>发送POST请求</button>
        <button>发送PUT请求</button>
        <button>发送DELETE请求</button>
    </div>

    <script>
        //获取按钮
       const btns= document.querySelectorAll("button");
    console.log(btns)
       //get
       btns[0].onclick=function(){
      
      
           //发送AJAX请求

            axios(
              {
      
      
                  //请求方式
              method: 'GET',
              url: "http://localhost:3000/persons",
              params: {
      
      
                  id:1
              }
             }

           ).then((response) => {
      
      
                console.log(response)
               
            });
        }
    </script>
</body>

简单写法

 btns[0].onclick=function(){
    
    
           //发送AJAX请求

        axios.get("http://localhost:3000/persons",{
    
    params:{
    
    id:1}}).then((response) => {
    
    
            console.log(response.data)
        });
        }

在这里插入图片描述

post请求

注意post请求参数是data时默认发送的数据格式是json格式参数

btns[1].onclick=function(){
    
    
          axios({
    
    
              method: 'POST',
              url: "http://localhost:3000/persons",
              data:{
    
    
                  name:"dyk",
                  age:18
              }
          }).then((response) => {
    
    
            console.log(response.data)
          });
        }

简写

axios.post("http://localhost:3000/persons",{
    
    name:'dyk123',age:21}).then(response =>{
    
    
            console.log(response.data)
        })

如果想发urlencoded形式

btns[1].onclick=function(){
    
    
          axios({
    
    
              method: 'POST',
              url: "http://localhost:3000/persons",
           
            headers:{
    
    'Content-Type':'application/x-www-form-urlencoded'},
            data:'name=cb&age=20'
          }).then((response) => {
    
    
            console.log(response.data)
          });
        }

put请求

axios({
    
    
              method: 'PUT',
              url: " http://localhost:3000/persons/1",
              data: {
    
    
                
                  name:'dyk12',
                  age:8
              }
            }).then((response) => {
    
    
            console.log(response.data)
          });

简写

 axios.put("http://localhost:3000/persons/1",{
    
    name:'rng',age:12}).then((response) => {
    
    
            console.log(response.data)
          });

delete请求

		axios({
    
    
              method: 'DELETE',
              url: "http://localhost:3000/persons/1",
              
            }).then((response) => {
    
    
            console.log(response.data)
          });

简写路径

可以看见上面每个请求都写了http://localhost:3000/很长一串路径,可以简写

axios.defaults.baseURL="http://localhost:3000";

后面所有的url都可以省略路径,但不能省略/

<!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">
    <title>axios</title>
   
</head>
<body>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <div class="container">
        <button>发送GET请求</button>
        <button>发送POST请求</button>
        <button>发送PUT请求</button>
        <button>发送DELETE请求</button>
    </div>

    <script>
        //获取按钮
       const btns= document.querySelectorAll("button");

       axios.defaults.baseURL="http://localhost:3000";
  
       //get
       btns[0].onclick=function(){
      
      
           //发送AJAX请求
        axios.get("/persons",{
      
      params:{
      
      id:1}}).then((response) => {
      
      
            console.log(response.data)
        });
        }

        //post
        //添加数据
        btns[1].onclick=function(){
      
      
  
        axios.post("/persons",{
      
      name:'dyk123',age:21}).then(response =>{
      
      
            console.log(response.data)
        })
        }

        btns[2].onclick=function(){
      
      
    

        axios.put("/persons/1",{
      
      name:'rng',age:12}).then((response) => {
      
      
            console.log(response.data)
          });
        }

        btns[3].onclick=function(){
      
      
            axios({
      
      
              method: 'DELETE',
              url: "/persons/2",
              
            }).then((response) => {
      
      
            console.log(response.data)
          });
        }
    </script>
</body>
</html>

axios的get请求禁止缓存

用axios拦截器拦截请求,为get请求添加时间戳

//axios请求拦截器
axios.interceptors.request.use(config => {
    
    
	if (/get/i.test(config.method)) {
    
     //判断get请求
		config.params  =  config.params || {
    
    };
		config.params.t = Date.parse(new Date())/1000; //添加时间戳
	}
    return config;
}, error => {
    
    
    return Promise.reject(error);
})


猜你喜欢

转载自blog.csdn.net/qq_44866153/article/details/119698260