fetch 是新的游览器对象, 等同于 XMLHttpRequest对象 。它提供了许多与 XMLHttpRequest 相同的功能, fetch 会先发起一个 option 的请求,确定是否连接成功,然后再发送正式的请求 .
fetch请求参数
常用配置项
- method(String): HTTP请求方法,默认为Get(Get,Post,Put,Delete)
- body(String): HTTP的请求参数
- headers(Object):HTTP的请求头,默认为{}
fetch(url, {
// options
}).then(function(response) {
//response
}, function(error) {
//error
})
1、Get请求方式的参数传递
//传参写法一
fetch('http://localhost:3000/books?id=123',{
method:'get'
}).then(function(data){
return data.text();
}).then(function(data){
console.log(data);
})
//后台接口
app.get('/books',(req,res)=>{
res.send('传统的url传参'+req.query.id)
})
//传参写法二
fetch('http://localhost:3000/books/123',{
method:'get'
}).then(function(data){
return data.text();
}).then(function(data){
console.log(data);
})
//后台接口
app.get('/books/:id',(req,res)=>{
res.send('Restful的url传参'+req.params.id)
})
2、Delete请求方式的参数传递
//传参写法一
fetch('http://localhost:3000/books/123',{
method:'delete'
}).then(function(data){
return data.text();
}).then(function(data){
console.log(data);
})
3、Post请求方式的参数传递
fetch('http://localhost:3000/books',{
method:"post",
headers:{
"Content-type":"application:/x-www-form-urlencoded:charset=UTF-8"
},
body:"name=xiaochen&password=123456"
}).then(function(res){
res.json().then(json => {
console.log(json.result)
})
}).catch(function(error){
console.log(error);
});