目錄
一、Axios概述
二、Axios入門案例
三、Axios請求方式别名
一、Axios概述
Axios對原生的AJAX進行封裝,簡化書寫
Axios 是一個基于 promise 網絡請求庫,作用于node.js 和浏覽器中。 它是 isomorphic 的(即同一套代碼可以運作在浏覽器和node.js中)。在服務端它使用原生 node.js
http
子產品, 而在用戶端 (浏覽端) 則使用 XMLHttpRequests。
特性
- 從浏覽器建立XMLHttpRequests
- 從 node.js 建立http 請求
- 支援Promise API
- 攔截請求和響應
- 轉換請求和響應資料
- 取消請求
- 自動轉換JSON資料
- 用戶端支援防禦XSRF
官網位址:起步 | Axios 中文文檔 | Axios 中文網 (axios-http.cn)
https://www.axios-http.cn/docs/intro
二、Axios入門案例
1、引入axios的js檔案
在html中引入:
<script src="js/axios-0.18.0.js"></script>
2、使用axios發送請求(get及post),并擷取響應結果
<script>
//1.get
axios({
method:"get",
url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan"
}).then(function (resp) {
alert(resp.data);
})
//2.post
axios({
method:"post",
url:"http://localhost:8080/ajax-demo/axiosServlet",
data:"username=zhangsan"
}).then(function (resp) {
alert(resp.data);
})
</script>
AxiosServlet代碼:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/axiosServlet")
public class AxiosServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("get...");
//1. 接收請求參數
String username = request.getParameter("username");
System.out.println(username);
//2.響應資料
response.getWriter().write("hello Axios");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("post...");
this.doGet(request, response);
}
}
執行結果:
通路02-axios-demo.html時get請求結果:
通路02-axios-demo.html時post請求結果及控制台結果:
三、Axios請求方式别名
為了友善起見,Axios已經為所有支援的請求方法提供了别名
axios.get(url[,config[)
axios.delete(url[,config])
axios.head(url[,config])
axios.options(url[,config])
axios.post(url[,data[,config]])
axios.put(url[,data[,config]])
axios.patch(url[,data[,config]])
方法名 | 作用 |
get(url) | 發送GET請求 |
post(url,請求參數) | 發送POST方式請求 |
發送get請求
axios.get("url")
.then(function (resp){
alert(resp.data);
});
示例:
axios.get("http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan").then(function (resp) {
alert(resp.data);
})
發送post請求
axios.get("url","參數")
.then(function (resp){
alert(resp.data);
axios.post("http://localhost:8080/ajax-demo/axiosServlet","username=zhangsan").then(function (resp) {
alert(resp.data);
})