已复制
全屏展示
复制代码

JavaScript之fetch获取后端数据


· 2 min read

一. API接口准备

安装依赖

简单用 flask 启动一个server,准备接口数据。

pip install flask-restful
pip install flask_cors

模拟数据

新建文件 app.py

import time
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from flask_cors import CORS

resp_header = {
    'Content-Type': 'application/json',
}
app = Flask(__name__)
api = Api(app)
CORS(app, origins='*', methods=['GET', 'POST', 'PUT'])

parser = reqparse.RequestParser()
parser.add_argument('username', type=str, help='username')


class HelloWorld(Resource):
    def get(self):
        args = request.args
        return {'hello': args.get('username'), 'method': 'get'}, 200, resp_header

    def post(self):
        args = parser.parse_args()
        return {'hello': args.get('username'), 'method': 'post'}, 200, resp_header


class TimeoutCustom(Resource):
    def get(self):
        time.sleep(10)
        return {'hello': 'longtime', 'method': 'get'}, 200, resp_header


api.add_resource(HelloWorld, '/hello')
api.add_resource(TimeoutCustom, '/longtime')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=9000)

启动 flask 服务

$ python app.py
 * Serving Flask app 'app'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:9000
 * Running on http://192.168.3.107:9000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 114-452-963

二. JS 获取数据

get获取数据

const data_get = async () => {
    const response = await fetch("http://localhost:9000/hello?username=yuziyue1");
    const ret = await response.json();
    return ret;
}
const ret = await data_get();
console.log("ret:", ret);

post获取数据

fetch 函数 也可以传入第二个参数,显示指定请求方法post,以及一些自定义header。

const data_post = async () => {
    // 传递给后端的数据
    const req_data = {username: "yuziyue2"}
    const response = await fetch("http://localhost:9000/hello", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(req_data),
    })
    return await response.json()
}
const ret = await data_post();
console.log("ret:", ret);

终止fetch

当某个请求非常耗时,我们想取消时。

<!DOCTYPE html>
<html>

<head>
    <title>fetch测试</title>
</head>

<body>
    <div>
        <button id="download">download</button>
        <button id="abort">abort</button>
    </div>
    <script>
        let controller = new AbortController()
        let signal = controller.signal
        const url = "http://localhost:9000/longtime"

        const downloadBtn = document.querySelector("#download")
        const abortBtn = document.querySelector("#abort")

        downloadBtn.addEventListener("click", async () => {
            try {
                const response = await fetch(url, { signal })
                const ret = await response.json()
                console.log("Download complete", ret)
            } catch (error) {
                console.error(`Download error: ${error.message}`)
            }
        })

        abortBtn.addEventListener("click", () => {
            controller.abort()
            console.log("Download aborted")
            controller = new AbortController()
            signal = controller.signal
        })
    </script>
</body>

</html>

  • 参考资料
Using the Fetch API - Web APIs | MDN
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
🔗

文章推荐