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…
AIR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.