最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

HTTP routing of path through nginx - Stack Overflow

programmeradmin8浏览0评论

I want to build a simple chat application where each user has a list of chats stored on the backend. Each chat has a link-button in the frontend with the path /chat/<chatId>, so clicking on the link will result in a change of the URL (e.g. /chat/1). My Flask backend looks like this:

@app.route('/chat/<int:chatId>', methods=['GET'])
@cross_origin()
def chat(chatId: int):
   global chatHistory
   userId = session["user_id"]
   return jsonify( { "chat": [ history for h, history in enumerate(chatHistory[userId]) if h == chatId ] } )

and my JavaScript like this:

    // Function to fetch chat data from the server
    async function fetchChatData(chatId) {
        try {
            const response = await fetch(`/chat/${chatId}`);
            if (response.ok) {
                const chatData = await response.json();
                displayChat(chatData);
            }
        } catch (error) {
            console.error('Error fetching chat data:', error);
        }
    }

       // Function to display chat data
    function displayChat(chatData) {
        for(const entry of chatData) {
            console.log(entry);
        }
    }

    // Check if the current path is a chat route
    if (window.location.pathname.startsWith('/chat/')) {
        const chatId = window.location.pathname.split('/').pop();
        fetchChatData(chatId);
    }

    // Handle hash changes for SPA routing
    window.addEventListener('hashchange', () => {
        const newChatId = window.location.pathname.split('/').pop();
        if (newChatId) {
            fetchChatData(newChatId);
        }
    });

and my nginx config like this:

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

but every time I click on one of those button, nginx returns 404 File not found. Of course I don't want to create a file for every chat on the backend but I think it is nice to do the retrieving of the chat via the browser URL. Any ideas how I could implement this?

发布评论

评论列表(0)

  1. 暂无评论