一、axios入門
1、axios的作用
Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。
官方網站:http://www.axios-js.com
2、axios應用案例
step1:mybatis-plus中添加後端接口
依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
controller
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@GetMapping("/list")
public List<User> list(){
return userService.list();
}
}
啟動主類
訪問:
http://localhost:8080/user/list
step2:創建03-axios-demo文件夾
step3:復制axios.js至文件夾
step4:創建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="axios.js"></script>
<script>
//基於promise
axios({
method: 'get',
url: 'http://localhost:8080/user/list',
})
.then((response) => {
console.log('獲取數據成功', response)
})
.catch((error) => {
console.log('獲取數據失敗', error)
})
//另一種寫法
axios
.get('http://localhost:8080/user/list')
.then((response) => {
console.log('獲取數據成功1', response)
})
.catch((error) => {
console.log('獲取數據失敗1', error)
})
</script>
</body>
</html>
二、跨域
1、為什麼會出現跨域問題?
出於瀏覽器的同源策略限制。
所謂同源(即指在同一個域)就是兩個地址具有相同的協議(protocol)、主機(host)和端口號(port)
以下情況都屬於跨域:
跨域原因說明 |
示例 |
域名不同 |
www.jd.com 與 www.taobao.com |
域名相同,端口不同 |
www.jd.com:8080 與 www.jd.com:8081 |
二級域名不同 |
item.jd.com 與 miaosha.jd.com |
http和https也屬於跨域。
如果域名和端口都相同,但是請求路徑不同,不屬於跨域,如:www.jd.com/item 和 www.jd.com/goods
同源策略會阻止一個域的javascript腳本和另外一個域的內容進行交互。
而我們剛才是從localhost:5500端口去訪問localhost:8080端口,這屬於端口不同,跨域了。
2、解決跨域問題
Spring早就給我們提供了解決方案,我們隻需要在對應controller上添加一個註解就可以了
我們在 UserController 類上添加跨域標簽@CrossOrigin,再進行測試,則測試成功!
@CrossOrigin //解決跨域問題
三、自定義配置
1、配置axios實例
可以對axios進行配置,簡化代碼的編寫
//使用自定義配置
const request = axios.create({
baseURL: 'http://localhost:8080', //url前綴
timeout: 1000, //超時時間
headers: {'token': 'helen123456'} //攜帶令牌
})
2、配置請求參數
這樣,遠程接口的url地址就可以修改成相對路徑了
//基於promise
//註意:這裡使用了前面定義的request
request({
method:'get',
url:'/user/list'
}).then(response => {
console.log('獲取數據成功', response)
}).catch(error => {
console.log('獲取數據失敗', error)
})
四、攔截器
在請求或響應被 then 或 catch 處理前攔截他們。
1、請求攔截器
在發送axios請求前,可以攔截請求,對請求做一些處理
// 請求攔截器
request.interceptors.request.use(
function (config) {
// 在發送請求之前做些什麼,例如:在請求頭中攜帶一個令牌
config.headers.token = 'helen123456'
return config
},
function (error) {
// 對請求錯誤做些什麼
return Promise.reject(error)
}
)
發送請求時,在請求頭中會攜帶這個token
![](https://news.xinpengboligang.com/upload/keji/4ded206a850ff4a7c02a0efe6883768a.jpeg)
2、響應攔截器
在發送完請求,獲取到響應後,可以對響應做一些處理,再返回給前端用戶
// 添加響應攔截器
request.interceptors.response.use(
function (response) {
// 對響應數據做點什麼,例如:使用response.data替代response,簡化前端拿到的數據結果
return response.data
},
function (error) {
// 對響應錯誤做點什麼
return Promise.reject(error)
}
)