<template>
<div>{{ msg }}</div>
</template>
<script>
export default {
data: () => ({
msg: "",
}),
created() {
// 导入依赖
const axios = require("axios");
// axios.get 发出get请求
axios
.get("https://httpbin.ceshiren.com/get?id=123")
.then((result) => {
console.log("get请求 通过拼接url的形式传递参数");
// thenc快截键,then 接收响应
// result是响应数据
console.log(result);
this.msg = result.data;
})
.catch((err) => {
// catch接收可能会遇到的异常
console.log(err);
});
axios.get(
"https://httpbin.ceshiren.com/get",
{
params: {id: 123}
}
).then((result) => {
console.log("通过params 传递参数")
console.log(result)
}).catch((err) => {
console.log(err)
});
// axios 发送post请求
axios.post(
'https://httpbin.ceshiren.com/post',
{name: 'lili'}
).then((result) => {
console.log('post 请求 携带json请求体')
console.log(result)
}).catch((err) => {
console.log(err)
});
// post请求,传递form表单,先下载form-data,安装命令npm install form-data --save
// 导入依赖
const FormData = require('form-data')
// 实例化对象
const form = new FormData();
form.append('name', 'joker');
axios.post(
'https://httpbin.ceshiren.com/post',
form,
{'conten-type': 'application/x-www-form-urlencoded'}
).then((result) => {
console.log('post请求,表单格式请求体')
console.log(result)
}).catch((err) => {
console.log(err)
});
}
};
</script>
评论