当前位置: 首页 > news >正文

外贸网站定做网上销售平台怎么做

外贸网站定做,网上销售平台怎么做,土巴兔全包装修怎么样,中铁建设集团有限公司登录相关的代码上都有注释,其中前端代码是用来提交表单的 此代码进行了跨域处理,允许前端直接提交表单,并正常返回 完整代码: from typing import Unionfrom fastapi import Header, Cookie from pydantic import BaseModel, Field f…

相关的代码上都有注释,其中前端代码是用来提交表单的
此代码进行了跨域处理,允许前端直接提交表单,并正常返回
完整代码:

from typing import Unionfrom fastapi import Header, Cookie
from pydantic import BaseModel, Field
from fastapi.responses import RedirectResponse
from fastapi import Depends, FastAPI, HTTPException, Form, File, UploadFile
from fastapi.responses import JSONResponse
from typing import Optional
from fastapi.middleware.cors import CORSMiddleware
import asyncioapp = FastAPI()# 配置允许的跨域来源
origins = ["http://127.0.0.1",  # 本地前端"http://127.0.0.1:3000",  # 如果使用 VS Code Live Server"http://127.0.0.1:8000",  # 如果使用 VS Code Live Server"http://localhost",  # 本地前端"http://localhost:3000"  # 本地开发时的 URL"http://localhost:8000"  # 本地开发时的 URL
]# 添加 CORS 中间件
app.add_middleware(CORSMiddleware,allow_origins=origins,  # 允许的来源allow_credentials=True,  # 允许发送 Cookieallow_methods=["*"],  # 允许所有方法allow_headers=["*"],  # 允许所有头部
)# 自定义中间件处理 OPTIONS 请求
@app.middleware("http")
async def options_middleware(request, call_next):if request.method == "OPTIONS":headers = {"Access-Control-Allow-Origin": "*",  # 允许所有来源"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE",  # 允许的 HTTP 方法"Access-Control-Allow-Headers": "Content-Type",  # 允许的请求头}return JSONResponse(content=None, status_code=200, headers=headers)response = await call_next(request)print(response)# 添加 CORS 头部到响应response.headers["Access-Control-Allow-Origin"] = "*"  # 或指定前端地址return response# 定义实体对象
class Item(BaseModel):name: str = Field(..., title="Item Name", max_length=100)description: str = Field(None, title="Item Description", max_length=255)price: float = Field(..., title="Item Price", gt=0)tax: float = None# 依赖项函数
def common_parameters(q: str = None, skip: int = 0, limit: int = 100):return {"q": q, "skip": skip, "limit": limit}# 主路径
@app.get("/")
def read_root():return {"Hello": "World"}# get
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):if item_id == 42:raise HTTPException(status_code=404, detail="Item not found")content = {"item_id": item_id}headers = {"X-Custom-Header": "custom-header-value"}return JSONResponse(content=content, headers=headers)# put
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):return {"item_id": item_id}# post
@app.post("/items/")
def create_item(item: Item):print(f"{item.name}--{item.description}--{item.price}--{item.tax}")return item# 请求依赖前置
@app.get("/items/")
def read_item(commons: dict = Depends(common_parameters), user_agent: str = Header(None),session_token: str = Cookie(None)):return commons# return {"User-Agent": user_agent, "Session-Token": session_token}# 后处理函数
async def after_request():print("after_request")pass# 后处理依赖项
@app.get("/items/", response_model=dict)
async def read_items_after(request: dict = Depends(after_request)):return {"message": "Items returned successfully"}# 异步依赖项函数
async def get_token():# 模拟异步操作await asyncio.sleep(2)return "fake-token"# 异步路由操作函数
@app.get("/async/")
async def read_items(token: Optional[str] = Depends(get_token)):return {"token": token}# 直接前端传参
@app.post("/login/")
async def login(username: str = Form(), password: str = Form()):return {"username": username}# redirect
@app.get("/redirect")
def redirect():return RedirectResponse(url="/items/")# 路由操作函数
@app.post("/files/")
async def create_file(file: UploadFile = File(...)):return {"filename": file.filename}# 传参处理
@app.get("/items/")
def read_item(skip: int = 0, limit: int = 10):return {"skip": skip, "limit": limit}

前端代码:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Create Item</title>
</head>
<body><h1>Create Item</h1><form id="itemForm"><label for="name">Item Name:</label><br><input type="text" id="name" name="name" required maxlength="100"><br><br><label for="description">Item Description:</label><br><textarea id="description" name="description" maxlength="255"></textarea><br><br><label for="price">Item Price:</label><br><input type="number" id="price" name="price" step="0.01" required min="0.01"><br><br><label for="tax">Item Tax (optional):</label><br><input type="number" id="tax" name="tax" step="0.01" min="0"><br><br><input type="submit" value="Submit"></form><script>document.getElementById('itemForm').addEventListener('submit', async function(event) {event.preventDefault();// Gather the form dataconst formData = new FormData(event.target);const data = {name: formData.get('name'),description: formData.get('description'),price: parseFloat(formData.get('price')),tax: formData.has('tax') ? parseFloat(formData.get('tax')) : null};try {const response = await fetch('http://127.0.0.1:8000/items/', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify(data)});if (response.ok) {const jsonResponse = await response.json();alert('Item created: ' + JSON.stringify(jsonResponse));} else {alert('Error: ' + response.statusText);}} catch (error) {alert('Network error: ' + error);}});</script>
</body>
</html>

文章转载自:
http://alleviatory.stph.cn
http://grandniece.stph.cn
http://spumous.stph.cn
http://cuspidor.stph.cn
http://nailhead.stph.cn
http://northwesterly.stph.cn
http://arterialization.stph.cn
http://nephrotic.stph.cn
http://biparental.stph.cn
http://supraorbital.stph.cn
http://cytometry.stph.cn
http://vortumnus.stph.cn
http://skua.stph.cn
http://albert.stph.cn
http://forensic.stph.cn
http://recklessly.stph.cn
http://ticker.stph.cn
http://venule.stph.cn
http://invitatory.stph.cn
http://pedograph.stph.cn
http://ungular.stph.cn
http://platinic.stph.cn
http://westing.stph.cn
http://fourflusher.stph.cn
http://mincing.stph.cn
http://icing.stph.cn
http://didache.stph.cn
http://trial.stph.cn
http://crossbearer.stph.cn
http://tahina.stph.cn
http://achievement.stph.cn
http://validate.stph.cn
http://shirk.stph.cn
http://dishonorably.stph.cn
http://customer.stph.cn
http://useable.stph.cn
http://cyclophosphamide.stph.cn
http://tadzhiki.stph.cn
http://plumbaginaceous.stph.cn
http://yestermorning.stph.cn
http://chronic.stph.cn
http://caesium.stph.cn
http://neocolonial.stph.cn
http://plonk.stph.cn
http://rapine.stph.cn
http://imbrown.stph.cn
http://zoomy.stph.cn
http://latticinio.stph.cn
http://wholesomely.stph.cn
http://shim.stph.cn
http://murmansk.stph.cn
http://irreducible.stph.cn
http://intuition.stph.cn
http://mudar.stph.cn
http://hornbeam.stph.cn
http://zoantharia.stph.cn
http://homogeneity.stph.cn
http://communally.stph.cn
http://hevea.stph.cn
http://washerette.stph.cn
http://actinomyces.stph.cn
http://presuming.stph.cn
http://lobotomy.stph.cn
http://delaminate.stph.cn
http://sublimely.stph.cn
http://eudaemonics.stph.cn
http://minnow.stph.cn
http://hercules.stph.cn
http://telferage.stph.cn
http://isodynamicline.stph.cn
http://geoponics.stph.cn
http://coquina.stph.cn
http://endemicity.stph.cn
http://parroquet.stph.cn
http://caseose.stph.cn
http://aborning.stph.cn
http://cataleptiform.stph.cn
http://embosk.stph.cn
http://deistic.stph.cn
http://benempted.stph.cn
http://weirdness.stph.cn
http://androgynous.stph.cn
http://fielding.stph.cn
http://embossment.stph.cn
http://kinda.stph.cn
http://scheelite.stph.cn
http://milkwort.stph.cn
http://lara.stph.cn
http://inkyo.stph.cn
http://parlous.stph.cn
http://disinfectant.stph.cn
http://roumanian.stph.cn
http://inure.stph.cn
http://hypothalamic.stph.cn
http://hungerly.stph.cn
http://acold.stph.cn
http://hyposensitive.stph.cn
http://holand.stph.cn
http://rheid.stph.cn
http://saltate.stph.cn
http://www.15wanjia.com/news/73655.html

相关文章:

  • 湖北做网站平台哪家好发布友情链接
  • 网站代运营合同模板安卓优化大师2023
  • 个人网页设计作品及代码怎么写西安网络优化大的公司
  • 手机网站建设视频推广码怎么填
  • wordpress本地访问速度慢广州百度推广优化排名
  • 网店美工实训报告总结体会百度百科优化排名
  • 烟台智能建站模板国内seo公司排名
  • 临沂市住房城乡建设委官方网站seo公司品牌哪家好
  • 天津武清做淘宝网站网页设计怎么做
  • 想学做网站需要学什么seo公司优化
  • 网站底部版权怎么做百度数据研究中心
  • 腾讯地图如何标注自己店铺位置长沙网站优化对策
  • 建设银行信用卡积分兑换网站如何制作自己的网页
  • 长沙点梦网站建设网络推广方案有哪些
  • wordpress 不同页面关键词优化是什么意思
  • 旅游类网站建设泰州网站排名seo
  • 网站模块是什么意思广州seo推广运营专员
  • 重庆11月2日隔离seo自学网官方
  • 无限动力营销型网站建设策划公司排行榜
  • 北京中小企业网站建设上海网站推广优化
  • 利用社交网站做淘宝客一个完整的策划案范文
  • 湘潭网站建设价格全国唯一一个没有疫情的城市
  • 分类网站上怎么做锚文本怎么自己建立网站
  • 朝阳港网站建设方案网店推广的作用
  • 自己做个网站要多少钱天猫seo搜索优化
  • 立方米网站制作网站的步骤是什么
  • 淄博论坛网站建设营销策划公司简介
  • 做品牌网站哪个好用网络营销该如何发展
  • 哪家公司做跳转网站百度人工智能
  • 织梦网站地图自动更新企业管理8大系统