接口调用fetch

接口调用Fetch

在这里插入图片描述

  • GET请求
    在这里插入图片描述
app.get('/books', (req, res) => {
    res.send('传统的url传递参数' + req.query.id)

})
app.get('/books/:id', (req, res) => {
    res.send('Restful的url传递参数' + req.params.id)

})
  • POST请求
 fetch('http://localhost:3000/books', {
                   method: 'post',
                   body: 'uname=list&pwd=123',
                   headers: {
                       'Content-Type': "application/x-www-form-urlencoded"
                   }
               })
               .then(function(data) {
                   return data.text()
               }).then(function(data) {
                   console.log(data)
               })



app.post('/books', (req, res) => {
    res.send('POST的url传递参数' + req.body.uname + req.body.pwd)

// body-parser提供body
// 支持json数据格式
})
  • PUT请求
    在这里插入图片描述

  • fetch响应结果
    return data.text() :将返回体处理为字符串类型
    returndata.json():返回结果和JSON.parse(responseText)一样

 //  fetch响应结果的数据格式  
        fetch('http://localhost:3000/json')
            .then(function(data) {
                return data.json()
             // return data.text()
            }).then(function(data) {
                // console.log(data.uname)
                // console.log(typeof data)object
                console.log(data)
或者 
	   // var obj = JSON.parse(data)
	// obj.name,obj,age,obj.gender
            })


app.get('/json', (req, res) => {
    res.json({
        uname: 'jack',
        uage: 12,
        gender: 'female'
    })

})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值