用axios发送htttp请求
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="lib/vue-2.6.10.js"></script>
<script src="lib/axios.min.js"></script>
</head>
<body>
<div id="app">
<input type="button" value="get请求" @click="getInfo">
<input type="button" value="post请求" @click="postInfo">
</div>
<script>
//创建一个vue实例
var vm = new Vue({
el: '#app',
data: {},
methods: {
getInfo() {//发起get请求
//当发起get请求后,通过.then来设置成功的回调函数
axios.get('https://v1.hitokoto.cn/').then(function (response) {
console.log(response);
//通过response拿到服务器的响应内容
}).catch(function (error) {
console.log(error);
});
//为给定ID的user创建请求
// axios.get('/user?ID=12345')
// .then(function (response) {
// console.log(response);
// })
// .catch(function (error) {
// console.log(error);
// });
//上面的请求也可以这样做
// axios.get('/user', {
// params: {
// ID: 12345
// }
// }).then(function (response) {
// console.log(response);
// }).catch(function (error) {
// console.log(error);
// });
},
postInfo() {//发起post请求
//手动发起的post请求,默认没有表单格式,所以,有的服务器处理不了
//通过post方法的第三个参数,设置提交的内容类型为普通表单数据格式
axios.post('https://v1.hitokoto.cn/', {
//这里可以添加参数
}).then(response => {
console.log(response);
}).catch(function (error) {
console.log(error);
});
//还可以通过配置参数进行请求
// 发送 POST 请求
// axios({
// method: 'post',
// url: '/user/12345',
// data: {
// firstName: 'Fred',
// lastName: 'Flintstone'
// },
// responseType: 'json';//默认 json 可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
// });
}
},
})
</script>
</body>
</html>
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。