关于调接口的方式:fetch调接口传参等

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);
});
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容