You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何搭建支持动态网页的HTTP服务器?解决CORS及静态服务局限

本地搭建支持动态网页的HTTP服务器方案

针对你的需求,以下是几个轻量且实用的Python服务器方案,同时解决CDN资源的CORS问题:

方案一:Flask(轻量首选,适合快速开发)

  1. 安装依赖
pip install flask flask-cors
  1. 编写服务器代码(保存为app.py)
from flask import Flask, render_template
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # 本地开发阶段允许所有跨域请求

# 动态路由,返回渲染后的页面
@app.route('/')
def index():
    # 模板文件需放在项目根目录的`templates`文件夹下
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)  # 开启调试模式,修改代码自动重启服务器
  1. 准备动态页面模板
    在项目根目录创建templates文件夹,里面新建index.html:
<!DOCTYPE html>
<html>
<head>
    <!-- 引用CDN的jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
    <h1>动态页面测试</h1>
    <script>
        $(document).ready(function() {
            alert('jQuery加载成功!');
        });
    </script>
</body>
</html>
  1. 启动服务器
python app.py

访问http://localhost:5000即可看到动态页面,jQuery可正常加载。

方案二:Django(适合复杂动态项目)

  1. 安装依赖
pip install django django-cors-headers
  1. 创建项目与应用
django-admin startproject mysite
cd mysite
python manage.py startapp myapp
  1. 配置项目(mysite/settings.py)
  • 在INSTALLED_APPS中添加'myapp'和'corsheaders'
  • 在MIDDLEWARE开头添加:
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    
  • 添加配置:CORS_ALLOW_ALL_ORIGINS = True(本地开发用)
  1. 编写视图(myapp/views.py)
from django.shortcuts import render

def index(request):
    return render(request, 'index.html')
  1. 配置路由(mysite/urls.py)
from django.contrib import admin
from django.urls import path
from myapp.views import index

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
]
  1. 准备模板文件
    在myapp目录下创建templates文件夹,放入和Flask方案中相同的index.html。

  2. 启动服务器

python manage.py runserver

访问http://localhost:8000即可。

方案三:FastAPI(现代异步框架)

  1. 安装依赖
pip install fastapi uvicorn python-multipart
  1. 编写服务器代码(保存为main.py)
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# 配置跨域
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

templates = Jinja2Templates(directory="templates")

@app.get("/")
async def read_root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})
  1. 准备模板文件
    创建templates文件夹和index.html(同前两个方案)。

  2. 启动服务器

uvicorn main:app --reload

访问http://localhost:8000即可。

关于CDN jQuery的CORS说明

知名CDN(如jsdelivr、cdnjs)的资源默认配置了跨域允许,只要你通过本地服务器(http://localhost)访问页面,而非直接打开file://协议的本地文件,就不会触发CORS限制。

内容的提问来源于stack exchange,提问作者Cooldude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 09:25:44