用axios發(fā)送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>
//創(chuàng)建一個vue實例
var vm = new Vue({
el: '#app',
data: {},
methods: {
getInfo() {//發(fā)起get請求
//當發(fā)起get請求后盐碱,通過.then來設(shè)置成功的回調(diào)函數(shù)
axios.get('https://v1.hitokoto.cn/').then(function (response) {
console.log(response);
//通過response拿到服務(wù)器的響應(yīng)內(nèi)容
}).catch(function (error) {
console.log(error);
});
//為給定ID的user創(chuàng)建請求
// 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() {//發(fā)起post請求
//手動發(fā)起的post請求,默認沒有表單格式沪伙,所以瓮顽,有的服務(wù)器處理不了
//通過post方法的第三個參數(shù),設(shè)置提交的內(nèi)容類型為普通表單數(shù)據(jù)格式
axios.post('https://v1.hitokoto.cn/', {
//這里可以添加參數(shù)
}).then(response => {
console.log(response);
}).catch(function (error) {
console.log(error);
});
//還可以通過配置參數(shù)進行請求
// 發(fā)送 POST 請求
// axios({
// method: 'post',
// url: '/user/12345',
// data: {
// firstName: 'Fred',
// lastName: 'Flintstone'
// },
// responseType: 'json';//默認 json 可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
// });
}
},
})
</script>
</body>
</html>
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者