fetch的基本使用

10 篇文章 0 订阅

服务器代码

const express = require('express')
const app = express()
const bodyParser = require('body-parser')
    // 处理静态资源
app.use(express.static('public'))
    // 处理参数
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// 设置允许跨域访问该服务
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Headers', 'mytoken');
    next();
});
app.get('/async1', (req, res) => {
    res.send('hello1')
})
app.get('/async2', (req, res) => {
    if (req.query.info == 'hello') {
        res.send('world')
    } else {
        res.send('error')
    }
})

app.get('/adata', (req, res) => {
    res.send('Hello axios!')
})
app.get('/axios', (req, res) => {
    res.send('axios get 传递参数' + req.query.id)
})
app.get('/axios/:id', (req, res) => {
    res.send('axios get (Restful) 传递参数' + req.params.id)
})
app.delete('/axios', (req, res) => {
    res.send('axios delete 传递参数' + req.query.id)
})
app.post('/axios', (req, res) => {
    res.send('axios post 传递参数' + req.body.uname + '---' + req.body.pwd)
})
app.put('/axios/:id', (req, res) => {
    res.send('axios put 传递参数' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd)
})

app.get('/axios-json', (req, res) => {
    res.json({
        uname: 'lisi',
        age: 12
    });
})


app.get('/fdata', (req, res) => {
    res.send('Hello Fetch!')
})
app.get('/books', (req, res) => {
    res.send('传统的URL传递参数!' + req.query.id)
})
app.get('/books/:id', (req, res) => {
    res.send('Restful形式的URL传递参数!' + req.params.id)
})
app.delete('/books/:id', (req, res) => {
    res.send('DELETE请求传递参数!' + req.params.id)
})
app.post('/books', (req, res) => {
    res.send('POST请求传递参数!' + req.body.uname + '---' + req.body.pwd)
})
app.put('/books/:id', (req, res) => {
    res.send('PUT请求传递参数!' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd)
})

app.get('/json', (req, res) => {
    res.json({
        uname: 'lisi',
        age: 13,
        gender: 'male'
    });
})

app.get('/a1', (req, res) => {
    setTimeout(function() {
        res.send('Hello TOM!')
    }, 1000);
})
app.get('/a2', (req, res) => {
    setTimeout(function() {
        res.send('Hello JERRY!')
    }, 2000);
})
app.get('/a3', (req, res) => {
    setTimeout(function() {
        res.send('Hello SPIKE!')
    }, 3000);
})

// 路由
app.get('/data', (req, res) => {
    res.send('Hello World!')
})
app.get('/data1', (req, res) => {
    setTimeout(function() {
        res.send('Hello TOM!')
    }, 1000);
})
app.get('/data2', (req, res) => {
    res.send('Hello JERRY!')
})

// 启动监听
app.listen(3000, () => {
    console.log('running...')
})

1.fetch的基本用法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        fetch('http://localhost:3000/fdata').then(function(data) {
            //text()方法属于fetchAPI的一部分  它返回一个promise对象 用于获取后台的数据
            return data.text();
        }).then(function(data) {
            console.log(data);
        })
    </script>
</body>

</html>

2.fetch的请求参数

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //
        /* fetch('http://localhost:3000/books?id=123', {
                            method: 'get'
                        }).then(function(data) {
                            //text()方法属于fetchAPI的一部分  它返回一个promise对象 用于获取后台的数据
                            return data.text();
                        }).then(function(data) {
                            console.log(data);
                        }) */
        /* fetch('http://localhost:3000/books/123', {
            method: 'get'
        }).then(function(data) {
            //text()方法属于fetchAPI的一部分  它返回一个promise对象 用于获取后台的数据
            return data.text();
        }).then(function(data) {
            console.log(data);
        }) */

        fetch('http://localhost:3000/books/789', {
            method: 'delete'
        }).then(function(data) {
            //text()方法属于fetchAPI的一部分  它返回一个promise对象 用于获取后台的数据
            return data.text();
        }).then(function(data) {
            console.log(data);
        })
    </script>
</body>

</html>

3.fetch的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);
        }) */
        /* fetch('http://localhost:3000/books ', {
            method: 'post',
            body: JSON.stringify({
                uname: '战三',
                pwd: 456
            }),
            headers: {
                'Content-type': 'application/json'
            }
        }).then(function(data) {
            return data.text();
        }).then(function(data) {
            console.log(data);
        })
 */
fetch('http://localhost:3000/books/123 ', {
            method: 'put',
            body: JSON.stringify({
                uname: '战三',
                pwd: 456
            }),
            headers: {
                'Content-type': 'application/json'
            }
        }).then(function(data) {
            return data.text();
        }).then(function(data) {
            console.log(data);
        })

4.fetch响应结果的数据形式

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //
        /* 
         Fetch相应结果的数据格式
          */
        /* fetch("http://localhost:3000/json").then(function(data) {
            return data.json();
        }).then(function(data) {
            console.log(data);
        }) */
        fetch("http://localhost:3000/json").then(function(data) {
            return data.json();
        }).then(function(data) {
            console.log(data);
        })
    </script>
</body>

</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值