1. axios的基本使用
axios(config): 通用/最本質的發任意型別請求的方式
頁面結構:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>axios基本使用</title>
<link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
<div class="container">
<h2 class="page-header">基本使用</h2>
<button class="btn btn-primary"> 發送GET請求 </button>
<button class="btn btn-warning" > 發送POST請求 </button>
<button class="btn btn-success"> 發送 PUT 請求 </button>
<button class="btn btn-danger"> 發送 DELETE 請求 </button>
</div>
</body>
</html>
請求的Json資料:
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
},
{
"id": 2,
"title": "CQUT-ZTJ",
"author": "TJ"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
},
{
"body": "喜大普奔",
"postId": 2,
"id": 2
}
],
"profile": {
"name": "typicode"
}
}
JS代碼:
axios函式回傳的是Promise物件
<script>
//獲取按鈕
const btns = document.querySelectorAll('button');
//第一個
btns[0].onclick = function () {
//發送 AJAX 請求
axios({
//請求型別
method: 'GET',
//URL
url: 'http://localhost:3000/posts/2',
}).then(response => {
console.log(response);
});
}
//添加一篇新的文章
btns[1].onclick = function () {
//發送 AJAX 請求
axios({
//請求型別
method: 'POST',
//URL
url: 'http://localhost:3000/posts',
//設定請求體 這里不用設定id
data: {
title: "今天天氣不錯, 還挺風和日麗的",
author: "張三"
}
}).then(response => {
console.log(response);
});
}
//更新資料
btns[2].onclick = function () {
//發送 AJAX 請求
axios({
//請求型別
method: 'PUT',
//URL
url: 'http://localhost:3000/posts/3',
//設定請求體
data: {
title: "今天天氣不錯, 還挺風和日麗的",
author: "李四"
}
}).then(response => {
console.log(response);
});
}
//洗掉資料
btns[3].onclick = function () {
//發送 AJAX 請求
axios({
//請求型別
method: 'delete',
//URL
url: 'http://localhost:3000/posts/3',
}).then(response => {
console.log(response);
});
}
</script>
運行結果:
-
發送GET請求:

-
發送POST(新增資料)請求:

-
發送 PUT(更新) 請求

-
發送 DELETE 請求

2. axios其他方式發送請求
- axios(url[, config]): 可以只指定 url 發 get 請求
- axios.request(config): 等同于 axios(config)
- axios.get(url[, config]): 發 get 請求
- axios.delete(url[, config]): 發 delete 請求
- axios.post(url[, data, config]): 發 post 請求
- axios.put(url[, data, config]): 發 put 請求
頁面結構同上,JS示例代碼為:
<script>
//獲取按鈕
const btns = document.querySelectorAll('button');
//發送 GET 請求
btns[0].onclick = function(){
// axios()
axios.request({
method:'GET',
url: 'http://localhost:3000/comments'
}).then(response => {
console.log(response);
})
}
//發送 POST 請求
btns[1].onclick = function(){
// axios()
axios.post(
'http://localhost:3000/comments',
{
"body": "喜大普奔",
"postId": 2
}).then(response => {
console.log(response);
})
}
</script>
3. axios請求回應結構分析

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/297870.html
標籤:其他
上一篇:【Java 虛擬機原理】Class 位元組碼二進制檔案分析 一 ( 位元組碼檔案附加資訊 | 魔數 | 次版本號 | 主版本號 | 常量池個數 )
