作者原文
1要使用axios跨域请求数据,则需要进行一下这几个步骤哦。
- 要使用axios,就必须下载axios这个库,可以有一下几个途径:
1、使用 npm install axios 或者 yarn add axios
2、可以之间使用线上cdn:<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>
- 需要从后端那里获得数据api接口地址。本次模拟数据是从JSONPlaceholder官网上随机获取的一个api接口。
- 需要了解到axios是基于 Promise + XMLHttpRequest 的,axios的底层还是ajax的。所以要知道全局函数axios.get(url)它返回的是一个Promise对象,最后还是需要一个变量容器来接收的。
- 接收到的Promise 还需要对之进行成功回调与失败回调处理。
以下是我的例子(嘻嘻):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>前端与后台交互之axios</title>
</head>
<script src="../node_modules/axios/dist/axios.js"></script>
<script>
var url = 'http://jsonplaceholder.typicode.com/albums';
var p = axios.get(url);
p.then((response)=>{
console.log(response);
if(response.status === 200){
console.log(response.data);
}
},(error)=>{
});
console.log(p);
</script>
<body>
</body>
</html>
最后通过服务器开启网页的时候,在控制台打印的数据如下(表示成功返回响应信息):