Day 27 - axios

  • 利用 XMLHttpRequest 原理
  • 可用 Node.js 後端进行请求
  • 语法简短
  • 直觉化
  • return 的是 Promise,所以可以使用 then(),catch()等,也可以用 async function。

使用前要先载入Axios 套件,下面两个 CDN 择一使用,切记要先载入套件,再载入 JavaScript,因为程序码由上往下执行,若先载入 JavaScript 再载入 axios 套件会出错。

  • Using jsDelivr CDN:
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  • Using unpkg CDN:
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  • 若是在 Node.js 安装则要 npm install axios

当发送请求成功时,会得到一个 response object,而这个 response object 里面包含了许多内容,包含:

  • data - 从 server 取得的资料
  • status - server 回传的 HTTP 状态码
  • statusText - server 回传的 HTTP 状态讯息
  • headers - server 传送的 headers
  • config - request 提供的配置讯息

axios 可以使用许多请求方式(get, post, put, delete, patch, options, head...等),这边只介绍取得资料的方式:
axios.get(url, config)
例如:

axios.get("https://randomuser.me/api/?results=1").then(res => {
    console.log(res.data);
    console.log(res.status);
    console.log(res.headers);
    console.log(res.config);
});

来看看成功取得资料後得到的这个 response object 里的内容
res.data:
https://ithelp.ithome.com.tw/upload/images/20210929/20140282mY81OoOE4p.jpg
res.status: 因为成功取得资料所以会显示 200
res.headers:
https://ithelp.ithome.com.tw/upload/images/20210929/201402820CORuLjFse.jpg
res.config:
https://ithelp.ithome.com.tw/upload/images/20210929/20140282GRrtwc3fwP.jpg

参考资料:https://zetcode.com/javascript/axios/


<<:  Day 27:「流浪到淡水!」- 手风琴选单

>>:  【面试】coding interview

Vue.js 从零开始:Vue Router

Router 是什麽? Router翻译为路由,依照网址结构,网路的服务器才会知道什麽时候要提供资料...

[Day14] Boxenn 实作 Source Wrapper

Source Wrapper source wrapper 的职责很简单,他负责将外部资源的介面转换...

[Day 14] 阿嬷都看得懂的 style 标签怎麽用

阿嬷都看得懂的 style 标签怎麽用 昨天我们介绍了 CSS 选择器,所以终於知道该怎麽把独立收整...

[Day-2] R语言 - 分群是甚麽? (what's clustering)

您的订阅是我制作影片的动力 订阅点这里~ 若内容有误,还请留言指正,谢谢您的指教 ...