vue fetch 接口调用&参数传递
fetch概述
基本特性
- 更加简单的数据获取方式,功能更强大、更灵活,可以看做是xnr的升级版
- 基于Promise实现
语法结构
fetch(url).then(fn2) .then(fn3) ... .catch(fn)
fetch的基本用法
fetch('/abc').then(function(data){
//text()属于feych的API的一部分,返回的是一个Promise实例对象,用于获取后台返回的数据
return data.text);
}.then(data => {
console.log(data);
}))
fetch请求参数
常用配置选项
- method(String):HTTP请求方法,默认为GET(GET、POST、PUT、DELETE)
- body(String):HTTP的请求参数
- headers(Object):HTTP的请求头,默认{}
fetch('/abc',{
methods: 'GET'
})
.then(data => {
return data.text);
}.then(ret => {
//注意这里得到的才是最终的数据
console.log(ret);
}));
GET请求方式传递参数
fetch('/abc/123',{
methods: 'GET'
})
.then(data => {
return data.text);
}.then(ret => {
//注意这里得到的才是最终的数据
console.log(ret);
}));
后台获取数据
app.get('/abc/:id',(req,res) => {
res.send('Restful形式的URL传递参数!' + req.params.id);
})
DELETE请求方式传递参数
fetch('/abc/123',{
methods: 'DELETE'
})
.then(data => {
return data.text);
}.then(ret => {
//注意这里得到的才是最终的数据
console.log(ret);
}));
DELETE后台获取数据
app.delete('/abc/:id',(req,res) => {
res.send('delete形式的URL传递参数!' + req.params.id);
})
POST请求方式传递参数
fetch('/abc',{
methods: 'POST',
//用于传递实际参数
body : 'uname=list&pwd=123',
//进行配置 必须设置
headers:{
'Content-Type' : 'application/x-www-form-urlencode'
}
})
.then(data => {
return data.text);
}.then(ret => {
console.log(ret);
}));
后台获取数据
app.post('/abc',(req,res) => {
res.send('Restful形式的URL传递参数!' + req.bbody.uname + '---' + req.body.pwd);
})
POST请求方法的JSON参数传递
fetch('/abc',{
methods: 'POST',
body : JSON.stringify({
uname : 'list',
pwd : 123
}),
headers:{
'Content-Type' : 'application/json'
}
})
.then(data => {
return data.text);
}.then(ret => {
console.log(ret);
}));
PUT请求方式传递参数
fetch('/abc/123',{
methods: 'put',
body : JSON.stringify({
uname : 'list',
pwd : 123
}),
headers:{ 'Content-Type' : 'application/json' }}) .then(data => {
return data.text);
}.then(ret => {
console.log(ret);
})
);
后台获取数据
app.get('/abc/:id',(req,res) => {
res.send('put形式的URL传递参数!' + req.params.id + req.bbody.uname + '---' + req.body.pwd);
})
fetch响应结果
响应数据格式
- text():将返回体处理成字符串类型
- json():返回结果和JSON.parse(reponseText)一样
fetch('/abc')
.then(data => {
return data.text);
}.then(ret => {
//注意这里得到的才是最终的数据
console.log(ret);
}));

浙公网安备 33010602011771号