在原生html页面发起axios请求,首先需要先引入axios文件包,然后按照axios的请求方式发起请求即可,但如果页面在本地,那么请求一般会报错跨域问题,需要部署一下才能正确请求数据;
例子
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 本地引入axios -->
<script src="000/axios-master/lib/axios.js"</script>
<!-- -->
</head>
<body>
<button id="btn">axios使用get提交数据</button>
<button id="btn1">axios使用post提交数据</button>
<button id="btn2">直接使用axios发送get提交数据</button>
<button id="btn3">直接使用axios发送post提交数据</button>
<script>
var btn = document.querySelector("#btn");
btn.addEventListener("click",function (params) {
var url = "http://www.liulongbin.top:3006/api/get";
var paramsobj = {name:'zs',age:20};
axios.get(url,{params:paramsobj}).then(function (res) {
var data = res.data;
console.log(data);
});
});
document.querySelector("#btn1").addEventListener("click",function (params) {
var url = "http://www.liulongbin.top:3006/api/post";
var dataobj = {location:'zs',address:'zs'};
axios.post(url,{params:dataobj}).then(function (res) {
console.log(res.data);
});
})
document.querySelector("#btn2").addEventListener("click",function (params) {
var url = "http://www.liulongbin.top:3006/api/get";
var paramsdata = {name:'zss',age:20};
axios({
url:url,
method:'GET',
params:paramsdata
}).then(function (res) {
console.log(res.data);
});
});
document.querySelector("#btn3").addEventListener("click",function (params) {
var url = "http://www.liulongbin.top:3006/api/post";
var paramsdataa = {name:'钢铁侠',age:35};
axios({
url:url,
method:'POST',
data:paramsdataa
}).then(function (res) {
console.log(res.data);
});
});
</script>
</body>
</html>
请求模板
javascript
axios.get(url,{params:参数}).then(function(){
//回调函数
});
axios({
url:url,
method:'POST',//'GET'
data:paramsdataa,//post保留
params:paramsdataa,//get保留
}).then(function (res) {
console.log(res.data);
});
配置响应头
javascript
axios({
url: url,
method: "GET",
params: paramsdata,
//响应头
headers: {
"Access-Control-Allow-Origin": "*",
},
}).then(function (res) {
console.log("返回的结果", res.data);
});