fetch
fetch概述
1.基本特性
+ 更加简单的数据获取方式,功能更强大,更灵活,可以看作是xhr的升级版。
+ 基于Promise实现
2.语法结构
fetch(url).then(fn1)
.then(fn2)
....
.catch(fn)
案例:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>Document</title> 8 </head> 9 <body> 10 11 </body> 12 <script> 13 fetch('http://localhost:3000/a1') 14 .then(res => { 15 console.log(res) 16 return res.text() 17 }) 18 .then(res => { 19 console.log(res) 20 }) 21 </script> 22 </html>
fetch 请求参数
1.常用配置选项
+ method(string): HTTP请求方法,默认为GET,(GET, POST, PUT, DELETE)
+ body(string): HTTP的请求参数
+ headers(object): HTTP的请求头,默认为{}
2.get请求
代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <title>Document</title> 6 </head> 7 8 <body> 9 10 </body> 11 <script> 12 // 传统的URL传递参数 13 fetch('http://localhost:3000/books?id=1231231231', { 14 method: 'get' 15 }).then(res => res.text()) 16 .then(res => console.log(res)) 17 18 // restful形式的URL传递参数 19 fetch('http://localhost:3000/books1/66666666666', { 20 method: 'get' 21 }).then(res => res.text()) 22 .then(res => console.log(res)) 23 </script> 24 25 </html>
3.post请求
代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>Document</title> 9 </head> 10 11 <body> 12 13 </body> 14 <script> 15 16 // url 格式 17 fetch('http://localhost:3000/test1', { 18 method: 'post', 19 headers: { 20 'Content-Type': 'application/x-www-form-urlencoded' 21 }, 22 body: 'name=zhangsan&id=1231231231312' 23 }).then(res => res.json()) 24 .then(res => console.log(res)) 25 26 // json 格式 27 fetch('http://localhost:3000/test2', { 28 method: 'post', 29 headers: { 30 'Content-Type': 'application/json' 31 }, 32 body: JSON.stringify({ 33 name: 'zhangsan', 34 age: '18' 35 }) 36 }).then(res => res.json()) 37 .then(res => console.log(res)) 38 </script> 39 40 </html>
4.PUT 请求
PUT 的请求与POST相似。