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

ReactJS前端与FastAPI后端在Azure Web App上的WebSocket连接失败

Azure Web App部署后FastAPI与React的WebSocket连接失败问题

我搭建了基于FastAPI的Python后端和ReactJS的前端应用,本地运行时WebSocket可正常建立连接并通信,但部署到Azure Web App后,WebSocket无法与后端建立连接。两个Azure Web App实例分别采用Linux环境下的Python 3.9和NodeJS 18 LTS,应用的其他HTTP接口功能均正常。

前端WebSocket代码(真实域名替换为MYDOMAIN)

import React, { useEffect } from "react";

const WebSocketExample = () => {
    const socket = new WebSocket("wss://MYDOMAIN/ws/");

    useEffect(() => {
        socket.onopen = function (event) {
            console.log("WebSocket connected");
        };

        socket.onmessage = function (event) {
            console.log("Received message:", event.data);
        };

        socket.onclose = function (event) {
            console.log("WebSocket closed");
        };

        return () => {
            socket.close();
        };
    }, [socket]);

    function sendEvent() {
        const eventData = "Event data";
        socket.send(eventData);
        console.log("Sent event:", eventData);
    }

    return (
        <div>
            <h1>WebSocket Example</h1>
            <button onClick={sendEvent}>Send Event</button>
        </div>
    );
};

export default WebSocketExample;

后端FastAPI路由代码

from app.routes.crud import crud_router
from app.routes.login import login_router
from app.routes.security import security_router
from app.routes.configs import configs_router
from setup import app, root_logger

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi import  WebSocket
from fastapi.responses import JSONResponse, HTMLResponse
import uvicorn

app.include_router(login_router)
app.include_router(crud_router)
app.include_router(security_router)
app.include_router(configs_router)

app = FastAPI()
app.add_middleware( # necessary to allow requests from local services
    CORSMiddleware,
    allow_methods=["*"],
    allow_headers=["*"],
    allow_origins=[
        'http://localhost:3000',
        'https://MYDOMAIN',
    ],
    allow_credentials=True)

connected_clients = set()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    # Accept WebSocket connection
    await websocket.accept()

    # Add client to the connected clients set
    connected_clients.add(websocket)

    try:
        while True:
            # Receive event data from the client
            event_data = await websocket.receive_text() + 'wow'
            root_logger.info(f"WEBSOCKET received event data: {event_data}")

            # Process the event data (e.g., validate, update state)

            # Broadcast the event data to all connected clients
            for client in connected_clients:
                await client.send_text(event_data)
                root_logger.info(f"WEBSOCKET has sent data: {event_data}")
    except Exception as e:
        root_logger.error(f"WEBSOCKET has error: {e}")
    finally:
        # Remove client from the connected clients set
        connected_clients.remove(websocket)
        root_logger.info(f"WEBSOCKET has removed client: {websocket}")

if __name__ == '__main__':
    uvicorn.run('main:app', reload=True, port=8000)

浏览器控制台报错信息

webs.js:7 WebSocket connection to 'wss://MYDOMAIN/ws/' failed:  
WebSocketExample   @   webs.js:7 
renderWithHooks   @   react-dom.development.js:16305 
mountIndeterminateComponent  @   react-dom.development.js:20074 
beginWork    @   react-dom.development.js:21587 
beginWork$1  @   react-dom.development.js:27426 
performUnitOfWork    @   react-dom.development.js:26557 
workLoopSync @   react-dom.development.js:26466 
renderRootSync   @   react-dom.development.js:26434 
performConcurrentWorkOnRoot  @   react-dom.development.js:25738 
workLoop @   scheduler.development.js:266 
flushWork  @   scheduler.development.js:239 
performWorkUntilDeadline

我排查了大量资料但相关案例极少,暂时无法定位问题。

补充测试

编辑:后续测试发现,无CORS配置的简易后端可成功建立WebSocket连接,因此怀疑FastAPI的CORS中间件干扰了WebSocket连接,计划移除代码中的CORS配置,改用Azure Web App自带的CORS设置。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 04:12:36