POST数据流通

很好,这个问题问得非常关键。我们就以刚才 mini.html 的 POST 示例为例,看一看“张三”这一串字符是怎么一路流动的。

1. 你在输入框里敲“张三”:数据先存在浏览器的页面里

HTML 里有一个输入框:

<input id="name-input" type="text" placeholder="请输入名字" />
  • 你在这个框里键盘输入“张三”
  • 浏览器把这个值放在这个输入框元素的一个属性里,叫 value
    可以理解为:页面里有一个对象 name-input,它的 value = "张三"

2. 点按钮时,JS 把“张三”读到变量里

JS 代码里:

const nameInput = document.getElementById('name-input');

helloPostBtn.addEventListener('click', async () => {
    const name = nameInput.value.trim() || '匿名用户';
    // ...
});

这里发生了两件事:

  1. getElementById('name-input'):找到刚才那个输入框元素(就像 Python 中拿到一个对象引用)。
  2. 点击按钮时执行回调函数:
    • nameInput.value从输入框里读出当前值,就是“张三”
    • 赋给 JS 变量 name,所以现在:name === "张三"

可以类比 Python 伪代码:

name_input = 页面.find_by_id("name-input")
name = name_input.value.strip() or "匿名用户"

3. JS 把 name 放进一个 JSON 里,通过 HTTP POST 发送给后端

接着:

const res = await fetch('http://localhost:5001/api/hello_post', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ name: name })
});

这里:

  • { name: name } 是一个 JS 对象:{ name: "张三" }
  • JSON.stringify({ name: name }) 变成字符串:'{"name":"张三"}'
  • 这个字符串作为 HTTP 请求的 body 发给服务器

所以这一刻的“张三”:

  • 输入框的 value
    ➜ 变成 JS 变量 name
    ➜ 变成 JSON 文本中的 "name":"张三"
    ➜ 作为 HTTP POST 请求体 发往 http://localhost:5001/api/hello_post

4. Flask 后端收到请求,用 request.json 解析出“张三”

后端代码:

@app.route('/api/hello_post', methods=['POST'])
def hello_post():
    data = request.json or {}
    name = data.get('name', '匿名用户')
    return jsonify({
        "message": f"你好,{name},这是 POST 调用返回的结果!"
    }), 200

这一段的过程:

  1. HTTP 请求到了 Flask,对应到这个路由 /api/hello_post
  2. Flask 看请求头 Content-Type: application/json,就把请求体 '{"name":"张三"}' 按 JSON 解析:
    request.json 得到一个 Python 字典:{"name": "张三"}
  3. data.get('name', '匿名用户') 取出 "张三",赋值给变量 name

也就是说:

  • “张三”现在变成了 Python 字典里的值,再变成 Python 变量 name

5. Flask 把“张三”拼进返回的 JSON,再发回给前端

继续后端代码:

return jsonify({
    "message": f"你好,{name},这是 POST 调用返回的结果!"
}), 200

假设 name = "张三",那就是:

jsonify({"message": "你好,张三,这是 POST 调用返回的结果!"})

Flask 会把这个 Python 字典转成 JSON 字符串:

{"message": "你好,张三,这是 POST 调用返回的结果!"}

作为 HTTP 响应的 body 从服务器发回浏览器。


6. 前端 JS 收到响应,把文字显示在页面上

回到前端:

const data = await res.json();
resultPostDiv.textContent = '后端返回:' + JSON.stringify(data);

这里:

  1. res.json() 把响应体的 JSON 字符串解析成 JS 对象:
    data = { message: "你好,张三,这是 POST 调用返回的结果!" }
  2. JSON.stringify(data) 再次变成字符串:
    {"message":"你好,张三,这是 POST 调用返回的结果!"}
  3. resultPostDiv.textContent = ... 把这串文字放进页面里的 <div id="result-post"> 里,你肉眼看到的就是这一行。

把整条链路压缩成一行

浏览器输入框(value="张三")
➜ JS 变量 name
➜ HTTP POST 请求体 JSON "name": "张三"
➜ Flask request.json['name'](Python 变量)
➜ Flask 返回 JSON "message": "你好,张三,..."
➜ 前端 data.message
➜ 页面上的文字显示出来

mini.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>前端调用后端最小示例</title>
</head>
<body>
<h1>前端调用后端 REST API 示例</h1>

<!-- 按钮 -->
<button id="hello-btn">测试:hello_my_project</button>

<!-- 显示结果的区域 -->
<div id="result" style="margin-top: 8px; color: blue;"></div>

<!-- POST 示例 -->
<h2>2. POST /api/hello_post</h2>
<input id="name-input" type="text" placeholder="请输入名字"/>
<button id="hello-post-btn">测试:hello_post (POST)</button>
<div id="result-post" style="margin-top: 8px; color: green;"></div>

<!-- 纯 JS,不依赖任何框架 -->
<script>

    // ------- GET 示例 -------
    // 1. 拿到按钮和结果区域
    const helloBtn = document.getElementById('hello-btn');
    const resultDiv = document.getElementById('result');

    // 2. 给按钮绑定点击事件
    helloBtn.addEventListener('click', async () => {
        // 修改按钮状态
        helloBtn.disabled = true;
        const oldText = helloBtn.textContent;
        helloBtn.textContent = '测试中...';

        resultDiv.textContent = '正在调用后端接口...';

        try {
            // 3. 用 fetch 调用后端 Flask 接口
            const res = await fetch('http://localhost:5001/api/hello_my_project', {
                method: 'GET'
            });

            // 4. 把返回内容解析成 JSON
            const data = await res.json();

            // 5. 把 JSON 显示在页面上
            resultDiv.textContent = '后端返回:' + JSON.stringify(data);
        } catch (err) {
            resultDiv.textContent = '调用失败:' + err.message;
        } finally {
            // 恢复按钮
            helloBtn.disabled = false;
            helloBtn.textContent = oldText;
        }
    });

    // ------- POST 示例 -------
    const nameInput = document.getElementById('name-input');
    const helloPostBtn = document.getElementById('hello-post-btn');
    const resultPostDiv = document.getElementById('result-post');

    helloPostBtn.addEventListener('click', async () => {
        const name = nameInput.value.trim() || '匿名用户';

        helloPostBtn.disabled = true;
        const oldText = helloPostBtn.textContent;
        helloPostBtn.textContent = '测试中...';
        resultPostDiv.textContent = '正在调用 /api/hello_post ...';

        try {
            const res = await fetch('http://localhost:5001/api/hello_post', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({name: name})
            });

            const data = await res.json();
            resultPostDiv.textContent = '后端返回了:' + JSON.stringify(data);
        } catch (err) {
            resultPostDiv.textContent = '调用失败:' + err.message;
        } finally {
            helloPostBtn.disabled = false;
            helloPostBtn.textContent = oldText;
        }
    });

</script>
</body>
</html>

后端接口

@app.route('/api/hello_post',methods=['POST'])
def hello_post():
    data = request.json or {}
    name= data.get('name','匿名用户')
    return jsonify({
        'message':f'你好,{name},这是POST调用返回的结果!'
    }),200
posted @ 2025-12-13 23:52  小翔子  阅读(2)  评论(0)    收藏  举报