(1)使用get
test.json文件
{
"list":[111,222,333]
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="box">
<button @click="handleClick">click</button>
{{list}}
</div>
<script>
var obj = {
data(){
return{
list:[]
}
},
methods: {
handleClick(){
// 基于promise
fetch("./test.json")
.then(
// res=>{return res.json()}
res=>res.json() // 简写 返回请求头响应头的一些信息
)
.then(res=>{
console.log(res,'res')
this.list = res.list
})
// fetch("./test.json")
// .then(
// res=>res.text() // 不确定是json格式 用text保险
// )
// .then(res=>{
// console.log(res,'res')
// })
}
},
}
Vue.createApp(obj).mount('#box')
</script>
</body>
</html>
遇到报错如下
安装插件 Preview on Web Server (使用Open with Live Server会有点小bug)
(2)使用post
1)安装工具 帮助创建接口 npm i json-server -g 允许跨域
2)启动命令 使用json-server --watch .\test2.json 访问文件;中间报错是json文件内容格式不对,修改一下
3)访问http://localhost:3000/list ;如果遇到禁止运行脚本就用管理员身份设置 set-ExecutionPolicy RemoteSigned
4)代码部分
test2.json文件
{
"list": [
{
"name": "seki",
"age": 18,
"id": "1"
}
]
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="box">
<button @click="handleClick">click</button>
{{list}}
</div>
<script>
var obj = {
data(){
return{
list:null
}
},
methods: {
handleClick(){
// 基于promise
// fetch("http://localhost:3000/list")
// .then(res=>res.json())
// .then(res=>{
// console.log(res,'res')
// this.list = res
// })
// 方式2
var params ={
name:'cj',
age:20
}
fetch("http://localhost:3000/list",{
method:"POST", // post POST 都可以
headers:{
'Content-Type':'application/json', // 不同请求头入参格式不一样
},
body:JSON.stringify(params)
}).then(res=>res.json())
.then(res=>{
console.log(res)
})
// put 更新
// fetch("http://localhost:3000/list/2",{
// method:"put",
// headers:{
// 'Content-Type':'application/json',
// },
// body:JSON.stringify({name:'xiaoxin'})
// }).then(res=>res.json())
// .then(res=>{
// console.log(res)
// })
// fetch("http://localhost:3000/list/2",{
// method:"delete",
// headers:{
// 'Content-Type':'application/json',
// },
// }).then(res=>res.json())
// .then(res=>{
// console.log(res)
// })
}
},
}
Vue.createApp(obj).mount('#box')
</script>
</body>
</html>