常用接口请求格式
fetch api请求接口
fetch('url接口地址')
.then(res=>{
return res.json();
}).then(todos => {
this.todos = todos;
})
这行请求的作用是使用fetch传输一个get请求
同时把获取到的数据赋值给之前在data()里定义的todos
fetch post请求接口
fetch('url'{
method:'POST',
body:JSON.stringify(this.todo),
headers:{
'Content-Type':'application/json'
}
}),then(
res=>{
return res.json();
}
).then(
//console.log(todo);
this.todos.unshift(todo);
)
所有使用fetch请求到的数据,都需要对请求进行回复格式的设定
即return res.json()
axios get请求接口
axios.get('url接口地址').then
(res => {
console.log(res);
})
这些函数尽量在生命周期钩子里定义
即页面渲染前mounted()
不需要对数据进行json解析
和fetch实现的是一样的
如果这里接受到的不是一个数组,而是一个单个的对象的话
那么可以直接进行打印,不许要定义数组
可以在data中定义一个空值
axios post请求接口
axios.post("url",this.todo).then(res =>{
console.log(res.data);
})
这里是将this.todo 使用post请求传给了后端
然后console.log打印出来的正是你所传递的数据
可以使用以下的代码将它去除json格式变成原本数据
this.todos.unshift(res.data);
这个代码写在.then 里