<!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">
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<title>Document</title>
</head>
<body>
<div id="app">
<button>发送get请求</button>
<button>发送post请求</button>
<button>发送put请求</button>
<button>发送delete请求</button>
</div>
</body>
<script>
//获取所有按钮dom
const btn = document.querySelectorAll("button")
//通过向axios传递相关配置来请求axios(comfig)--- comfig->配置项
axios({
method: "GET/POST",//请求方式
url: '/user/12345',//请求地址
data: { //只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
name: "lisi",
age: 17,
},
baseURL: "",//`baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对地址
headers: { 'X-Requested-With': 'XMLHttpRequest' },// `headers` 是即将被发送的自定义请求头
params: {
ID: 12345
},// `params` 是即将与请求一起发送的URL参数 必须是一个无格式对象(plain object)或 URLSearchParams 对象
timeout: 1000,//请求超时自动停止
})//配置项有很多,常用的是这几种
//请求方法的别名
//为方便起见,为所有支持的请求方法提供了别名
axios.request(config)
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]])
//栗子:
//除了使用axios来发送请求之外 还可以通过axios上自带的方法发送请求,
//各方法详细使用方法查看http://www.axios-js.com/zh-cn/docs/
btn[0].onclick = function () {//使用axios的request方法发送请求
axios.request({
method: "GET",//请求类型
url: "https://api.it120.cc/conner/shop/goods/category/all"//地址
}).then(response => {//响应的内容
console.log(response)
})
}
btn[1].onclick = function () {//post方法发送
axios.post(
"https://api.it120.cc/conner/shop/goods/category/all",
{
// "body": "qianqian",
// "postid": "123"
}).then(response => {
console.log(response)
})
}
//axios配置默认值defaults,写在发送请求前
//全局的 axios 默认值
//例如:
//设置默认的baseURL,在下面发送请求时如果不配置baseURL,将默认使用这个默认配置项
axios.defaults.baseURL = 'https://api.example.com';
// //设置默认的请求头common内容
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// //设置默认的请求头post形式
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//还可以通过自定义配置创建axios实例
//在这里配置默认项
//使用这种实例axios对象的方式好处:
//在需要请求多个不同域名的服务器时 可以很好的区分配置好相同的默认项后,请求不同的域名只需新建实例对象
const axi = axios.create({
baseURL: "https://api.it120.cc/conner",
headers: {"xx": "xxxx"},
})
//在这里填入请求方式和地址
axi.post("/shop/goods/category/all",{data: {name: "lisi"}}).then(response=>{
console.log(response)
})
const axis = axios.create({
baseURL: "https://api.it120.cc/conner",
})
axis.get("/shop/goods/category/all").then(response=>{
console.log(response)
})
</script>
</html>
AXIOS ->基础
最新推荐文章于 2024-09-13 23:24:03 发布