[学习笔记] 数据请求(二) --- Axios

[学习笔记] 数据请求(二) — Axios

认识 Axios

  • 文档

    Axios中文文档

  • 概要说明

    • Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
    • 特性:
      • 从浏览器中创建 XMLHttpRequests
      • 从 node.js 创建 http 请求
      • 支持 Promise API
      • 拦截请求和响应
      • 转换请求数据和响应数据
      • 取消请求
      • 自动转换 JSON 数据
      • 客户端支持防御 XSRF

简单使用 Axios

一、安装

  • 脚手架(npm)安装:

    此处为当前写法,请以官网描述为准:

    请前往 npm 官网 搜索 ‘axios’ —— Axios-npm

    $ npm install axios

  • 使用 cdn:

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

二、简单使用案例

2-1 请求案例

  • 简单 get 请求

    axios.get('https://jsonplaceholder.typicode.com/todos/1').then(res => {
         
        console.log(res.data); // 打印获取到的数据
    })
    .then(res => {
         
        console.log(res); // 打印获取到的数据
    })
    .catch(err => console.log(err));
    
  • post 请求

    Ps: 使用 jsonplaceholder,资源不会在服务器上真正更新,但会被仿造。

    所以:想展示上传数据后的数据,需要本地将返回结果 push 或者 unshift 到本地数组中

    数据准备:

    todo: {
         
    	"title": "William",
    	"completed": true
    }
    

    发起请求:

    axios.post('https://jsonplaceholder.typicode.com/todos', this.todo)
        .then(res => {
         
        	console.log(res.data); // 打印获取到的数据
    });
    

    返回结果:

    {
         
    	"id": 201,
    	"title": "William",
    	"completed": true
    }
    
  • 写法二:(以 post 请求为例,数据同上 todo

    // 发送 POST 请求
    axios({
         
      method: 'post',
      url: 'https://jsonplaceholder.typicode.com/todos',
      data: this.todo,
      timeout: 5000
    })
    .then(res => console.log(res.data))
    .catch(err => console.log(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值