fetch概述
看一个基本的例子:
服务端代码:
app.get('/fdata',(req,res)=>{setTimeout(function(){res.send('this is content retrived by fetch method')},3000)})
测试:
<script>fetch('http://127.0.0.1:9999/fdata').then((data) => {return data.text() // data.text()返回的是一个promise对象}).then((result) => {// 调用then这里获取的才是真正的数据console.log(result)})</script>
等了几秒以后控制台输出:
fetch请求参数
fetch之get请求参数
我们再看下面的代码:
// 服务端app.get('/books',(req,res)=>{setTimeout(function(){console.log(req.query)res.send('传统参数传递:' + JSON.stringify(req.query))},3000)})
// 这里我们用旧的方式传入参数,method:'get'写不写无所谓,默认就是getfetch('http://127.0.0.1:9999/books?id=123',{method:'get'}).then((data) => {return data.text()}).then((result) => {console.log(result)})
结果:
我们现在换restful风格的url:
那么在服务端我们也要修改一下路由:
这里要用:id
来接收传来的数据,express需要用req.params
来获得查询数据
结果:
这里有个细节注意一下:
这里的参数999传过去的时候,在服务端:
路由接收传来的参数的变量名是可以自定义的,不一定非要是id,保持统一就可以了
fetch之delete请求参数
// 服务端app.delete('/books/:id',(req,res)=>{setTimeout(function(){res.send('Delete请求参数传递:' + req.params.id)},3000)})
fetch('http://127.0.0.1:9999/books/666',{method:'delete'}).then((data) => {return data.text()}).then((result) => {console.log(result)})
结果:
fetch之post请求参数
发送x-www-form-urlencoded类型的数据上代码:
// 服务端const bodyParser = require('body-parser')// 配置body-parserapp.use(bodyParser.json())app.use(bodyParser.urlencoded({extended: false }))app.post('/books', (req, res) => {// body就是body-parser处理的console.log(req.body)res.send('Post请求参数传递:' + req.body.uname + '---' + req.body.pw)})
fetch('http://127.0.0.1:9999/books/',{method:'post',body:'uname=dean&pw=123456',headers:{'Content-Type':'application/x-www-form-urlencoded'}}).then((data) => {return data.text()}).then((result) => {console.log(result)})
发post请求主要就下面这些变化:method,请求体body,头部headers:
结果:
发送json类型的数据
// 服务端app.post('/books', (req, res) => {console.log(req.body)res.send('Post请求参数传递:' + req.body.uname + '---' + req.body.age)})
js代码需要这样修改:
结果:
fetch之put请求参数
app.put('/books/:id', (req, res) => {console.log('req.body:',req.body)console.log('req.params:',req.params)console.log('请求id:',req.params.id)res.send('Put请求参数传递:' + req.body.bname + '---' + req.body.bprice)})
注意这里::id
需要用req.params.id取值
结果:
fetch响应结果
我们看看如何用fetch的json API返回数据:
// 服务端app.get('/books/json', (req, res) => {// 调用express的json方法res.json({bname:'ES6',bprice:79})})
结果: