首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >GitHub Page 部署前端页面 请求本地 Flask get_time 接口

GitHub Page 部署前端页面 请求本地 Flask get_time 接口

作者头像
小田测测看
发布2026-06-17 19:28:37
发布2026-06-17 19:28:37
1240
举报

想法:免费白嫖githubpage在线页面

一个简洁的 index.html 页面,实现「请求本地 8001 端口的 /get_time 接口 → 页面展示时间」,同时适配 GitHub Page 部署,并通过脚本猫的 hook 对接本地 Flask 编写的 /get_time 接口。我会提供完整的前端页面Flask 后端代码(解决跨域),以及脚本猫对接的关键步骤。

一、先准备本地 Flask 后端(核心:解决跨域)

因为 GitHub Page 是静态页面,调用本地 8001 端口会触发跨域限制,所以 Flask 后端必须配置 CORS(跨域允许)。

1. Flask 后端代码(app.py
代码语言:javascript
复制
from flask import Flask, jsonify
from flask_cors import CORS  # 解决跨域核心
import datetime

app = Flask(__name__)
# 允许所有域名跨域访问(本地测试/脚本猫对接专用,生产可限定域名)
CORS(app, resources={r"/get_time": {"origins": "*"}})

# 定义 /get_time 接口,返回当前时间
@app.route('/get_time', methods=['GET'])
def get_time():
    # 获取当前时间(格式:年-月-日 时:分:秒)
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return jsonify({
        "code": 200,
        "msg": "success",
        "data": {"current_time": current_time}
    })

if __name__ == '__main__':
    # 启动服务:监听本地8001端口,允许局域网访问(脚本猫可对接)
    app.run(host='0.0.0.0', port=8001, debug=True)
2. 安装 Flask 依赖
代码语言:javascript
复制
pip install flask flask-cors
3. 启动后端
代码语言:javascript
复制
python app.py
# 启动成功提示:* Running on all addresses (0.0.0.0)
# * Running on http://127.0.0.1:8001

二、编写 index.html 页面(适配 GitHub Page)

页面功能:加载后自动请求 http://127.0.0.1:8001/get_time,展示时间,包含「刷新时间」按钮,处理加载 / 错误状态,代码极简且适配 GitHub Page 部署。

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>本地时间接口展示</title>
    <style>
        /* 极简样式,适配所有设备 */
        body {
            max-width: 600px;
            margin: 50px auto;
            font-family: Arial, sans-serif;
            text-align: center;
        }
        .container {
            padding: 20px;
            border: 1px solid #eee;
            border-radius: 8px;
            box-shadow: 02px10pxrgba(0,0,0,0.1);
        }
        .time-box {
            font-size: 24px;
            margin: 20px0;
            color: #1890ff;
        }
        .btn {
            padding: 10px20px;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .btn:hover {
            background: #096dd9;
        }
        .loading {
            color: #666;
        }
        .error {
            color: #ff4d4f;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>本地 /get_time 接口返回时间</h1>
        <div id="timeContent" class="loading">正在请求时间...</div>
        <button class="btn" onclick="fetchTime()">刷新时间</button>
    </div>

    <script>
        // 本地接口地址(部署到GitHub Page后,仅能访问本地8001,需确保后端启动)
        constAPI_URL = 'http://127.0.0.1:8001/get_time';

        // 页面加载后自动请求时间
        window.onload = fetchTime;

        // 核心:请求/get_time接口并展示
        functionfetchTime() {
            const timeContent = document.getElementById('timeContent');
            timeContent.className = 'loading';
            timeContent.innerText = '正在请求时间...';

            // 发送GET请求
            fetch(API_URL)
                .then(response => {
                    if (!response.ok) thrownewError('接口请求失败');
                    return response.json();
                })
                .then(data => {
                    if (data.code === 200) {
                        timeContent.className = 'time-box';
                        timeContent.innerText = `当前时间:${data.data.current_time}`;
                    } else {
                        thrownewError(data.msg || '接口返回异常');
                    }
                })
                .catch(error => {
                    timeContent.className = 'error';
                    timeContent.innerText = `请求失败:${error.message}\n请检查本地8001端口Flask服务是否启动`;
                });
        }
    </script>
</body>
</html>

三、部署到 GitHub Page 步骤

  1. 1. 新建 GitHub 仓库:比如命名为 curl-converter(和你之前的项目名一致)。
  2. 2. 上传文件:将 index.html 上传到仓库根目录(或 docs 目录)。
  3. 3. 开启 GitHub Page:
    • • 仓库 → Settings → Pages → Build and deployment → Source 选择「Deploy from a branch」;
    • • Branch 选择 main(或 master),目录选择 /(根目录)或 /docs
    • • 点击 Save,等待部署完成,会生成访问地址(如 https://你的用户名.github.io/仓库名/)。

四、脚本猫 Hook 对接本地 Flask 接口

脚本猫(油猴类脚本管理器)可通过 GM_xmlhttpRequest 调用本地 8001 端口的 /get_time 接口,以下是极简的脚本猫 hook 示例:

脚本猫脚本(对接 /get_time 接口)
代码语言:javascript
复制
// ==UserScript==
// @name         脚本猫对接本地get_time接口
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  调用本地8001端口的/get_time接口,获取时间
// @author       You
// @match        *://*/*  // 匹配所有页面,可限定为你的GitHub Page地址
// @grant        GM_xmlhttpRequest  // 必须授权,才能跨域请求本地接口
// ==/UserScript==

(function() {
    'use strict';

    // 调用本地/get_time接口
    functiongetLocalTime() {
        GM_xmlhttpRequest({
            method: "GET",
            url: "http://127.0.0.1:8001/get_time",
            onload: function(response) {
                const data = JSON.parse(response.responseText);
                if (data.code === 200) {
                    console.log("脚本猫获取本地时间:", data.data.current_time);
                    // 可自定义逻辑:比如在页面插入时间、发送通知等
                    alert(`脚本猫获取到本地时间:${data.data.current_time}`);
                }
            },
            onerror: function(error) {
                console.error("脚本猫请求失败:", error);
                alert("请确保本地8001端口的Flask服务已启动!");
            }
        });
    }

    // 页面加载后执行
    window.onload = getLocalTime;

    // 可选:添加页面按钮触发
    const btn = document.createElement('button');
    btn.innerText = "脚本猫获取本地时间";
    btn.style.position = "fixed";
    btn.style.top = "20px";
    btn.style.right = "20px";
    btn.style.padding = "10px";
    btn.style.background = "#1890ff";
    btn.style.color = "white";
    btn.style.border = "none";
    btn.style.borderRadius = "4px";
    btn.style.cursor = "pointer";
    btn.onclick = getLocalTime;
    document.body.appendChild(btn);
})();

关键注意事项

  1. 1. 跨域问题:GitHub Page 访问本地 8001 接口仅能在「本地浏览器」生效(因为 127.0.0.1 是本地地址),外网无法访问你的本地接口。
  2. 2. 服务启动:访问页面 / 运行脚本猫脚本前,必须确保 Flask 后端在本地 8001 端口启动。
  3. 3. 脚本猫权限:脚本必须声明 @grant GM_xmlhttpRequest,否则无法跨域请求本地接口。

总结

  1. 1. 核心文件:Flask 后端(解决跨域)+ index.html(请求接口展示时间)+ 脚本猫脚本(hook 对接);
  2. 2. 部署要点:GitHub Page 仅部署静态 index.html,接口请求仅本地有效;
  3. 3. 关键配置:Flask 加 CORS、脚本猫声明 GM_xmlhttpRequest 权限。

启动 Flask 后端 → 打开 index.html(或 GitHub Page 地址)→ 安装脚本猫脚本,即可完成全流程对接。

github仓库 https://github.com/FlowerOda/get_time

#githubpage

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2026-02-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 编程拾光 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、先准备本地 Flask 后端(核心:解决跨域)
    • 1. Flask 后端代码(app.py)
    • 2. 安装 Flask 依赖
    • 3. 启动后端
  • 二、编写 index.html 页面(适配 GitHub Page)
  • 三、部署到 GitHub Page 步骤
  • 四、脚本猫 Hook 对接本地 Flask 接口
    • 脚本猫脚本(对接 /get_time 接口)
  • 关键注意事项
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档