Cannot connect websocket via Nginx when using FastAPI

I’m trying to run a simple service with websocket to make it work through nginx. This is what my files look like (their code is below). When I run this on a local PC (Windows 10), it works correctly, but on vps (UBUNTU) with nginx there is no way for the connection to be established via websocket.
What am I doing wrong, please give me advice. I haven’t been able to solve this for seven days now! Thank you in advance

app.py

from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
import uvicorn

app = FastAPI()
templates = Jinja2Templates(directory="templates")
active_connections = []

@app.get("/", response_class=HTMLResponse)
def read_index(request: Request):
    return templates.TemplateResponse("index.html", {"request" : request})

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    active_connections.append(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await websocket.send_text(data)
    except WebSocketDisconnect:
        active_connections.remove(websocket)



@app.get("/send_message_{id_one}")
async def send_message(id_one: int):
    await active_connections[int(id_one)].send_text(f"{id_one} Hi, new message!")    
    return "Sending ui done"


if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8888)

=====================
The file is located in the templates folder index.html , code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WS Example</title>
</head>
<body>
    <h1>One-Two, Go To! WebSOCKET Example</h1>
    <input type="text" id="inputText" placeholder="Type something...">
    <button id="submitButton">Submit</button>
    <div id="container"></div>
    <script>
        // Create a WebSocket connection to the server
        const socket = new WebSocket("ws://123.45.67.89:3333/ws");
    
        // Function to display messages on the web page
        function showMessage(message) {
            const messageContainer = document.getElementById('container');
            const messageElement = document.createElement('div');
            messageElement.textContent = message;
            messageContainer.appendChild(messageElement);
        }
 
        // Event handler for when the connection is established
        socket.addEventListener('open', (event) => {
            showMessage('Connected to server...');
        });
 
        // Event handler for receiving messages from the server
        socket.onmessage = (event) => {
            showMessage("You sent : " + event.data)
        }
 
        // Event handler for when the connection is closed
        socket.addEventListener('close', (event) => {
            showMessage('Connection closed.');
        });
 
        const inputText = document.getElementById("inputText");
        const submitButton = document.getElementById("submitButton");
 
        submitButton.addEventListener("click", function() {
            const inputValue = inputText.value;
            socket.send(inputValue)
        });

       
    window.addEventListener('beforeunload', function() {
      socket.close();
    });
    
    </script>
</body>
</html>

=======================
nginx code:

map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

upstream websocket {
    server 123.45.67.89:3333;
    }

server {
    listen 3333;
    server_name 123.45.67.89;

    location / {
        proxy_pass http://127.0.0.1:8888;  
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /ws {
        proxy_pass http://127.0.0.1:8888/ws;  
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade"; #$connection_upgrade;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

When I switch to http://123.45.67.89:3333 then the HTML page loads, but in the developer tools (F12 Chrome) I see this error:

Here is a screenshot with an error:

================
I asked this question a few days ago in the “issues” of the official GITHUB FASTAPI and got advice there to visit https://fastapi.tiangolo.com/tutorial/cors/
I took some of the code from there and applied it to my project:

from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
from fastapi.middleware.cors import CORSMiddleware
import uvicorn

app = FastAPI()
templates = Jinja2Templates(directory="templates")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)
#I tried with and without the allow_credentials=True parameter
#allow_credentials=True,

active_connections = []

@app.get("/", response_class=HTMLResponse)
def read_index(request: Request):
    return templates.TemplateResponse("index.html", {"request" : request})

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    active_connections.append(websocket)
    try:
        while True: 
            data = await websocket.receive_text()
            await websocket.send_text(data)
    except WebSocketDisconnect:
        active_connections.remove(websocket)


@app.get("/send_message_{id_one}")
async def send_message(id_one: int):
    await active_connections[int(id_one)].send_text(f"{id_one} Hi, new message!")    
    return "Sending ui done"

if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8888)

but it didn’t work…

New contributor

AIR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật