[Day 27] 串接Api axios基本用法

完成的页面也不少了,距离完赛剩3天,就不刻画面了,先来串串api啦!

刚好可以把之前假资料的部分全部改为接api

首先需要安装axios套件

axios是甚麽?

官方文件:axios 是一个基於 Promise 的 HTTP 客户端,专门为浏览器和 node.js 服务

简单来说就是一个api工具,可以在前端传送/接收api到後端

安装 axios

npm install axios

引用 axios 包

记得有使用新工具都要在main.js里,引用package

import axios from 'axios'

使用 axios

官网有特别标注,在 CommonJS 中,如果要使用 axois 的方法或参数 ( ex: axios.),记得要用 require() 去import axios

const axios = require('axios').default;

// axios.<method> will now provide autocomplete and parameter typings

axios 基本语法

这边会介绍最常用到的 get / post

Get

get通常会用来跟後端拿取不需加密的资料,

get的参数会带在url上,例如 http://127.0.0.1/user?ID=12345

axios.get('/user', {
    params: { // 如果有参数才需要加param,没有的话可以不用写
      ID: 12345
    }
  })
  .then(function (response) { // 成功後要做的事
    console.log(response);
  })
  .catch(function (error) { // 失败後要做的事
    console.log(error);
  })
  .then(function () {      // 不管成功或失败都要做的事
    // always executed
  });

另外也支援 async/await 语法

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

Post

post通常用来传递比较重要的参数跟资料,跟get差别在於post不会把参数显示在URL中,

像是登入的帐密就要用post才不会被看光光

axios.post('/user', { // 参数要用大括号包起来
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) { // 成功後要做的事
    console.log(response);
  })
  .catch(function (error) {  // 失败後要做的事
    console.log(error);
  });

延伸阅读

浅谈 HTTP Method:表单中的 GET 与 POST 有什麽差别? - Soul & Shell Blog

什麽是REST? 认识 RESTful API 路由语义化设计风格|ALPHA Camp Blog


吐槽一下,axios的官方文件真的是蛮简易的

只有短短几句介绍跟一堆程序码 ><

明天来做一个api 实例,gogo


<<:  Day28_CSS语法11

>>:  大共享时代系列_026_第三方物流(Third-Party logistics,3PL)

Day06 - 随意玩之 OrderQuery/OrderPayQuery

昨天介绍了 OrderCreate,今天会把另外两个都介绍完! OrderQuery 主要功能:查询...

Day12帮HTML穿衣服罗(CSS)

如何穿上CSS? 有了前面那些HTML的基本观念那麽就可以进入CSS了 那麽如何帮HTML穿上CSS...

[Day 4] -『 GO语言学习笔记』- GO语言架构介绍

如本日主题,今天要来介绍一下Go语言的程序码架构,以下内容摘录自『 The Go Workshop ...

Day13_HTML语法10

单行文字方块(text) 让使用者输入单行的文字叙述,例如:姓名、地址、电话、信箱等等 使用<...

30天程序语言研究

今天是30天程序语言研究的第十五天,由於深度学习老师多让我们上了python的进阶课程里面包括之前没...