返回博客

JS Vue React 路由处理机制

本文探讨了 JavaScript、Vue 和 React 如何处理路由,并解释了 Nginx 配置中 `try_files` 指令的作用,以及如何通过它实现单页应用的路由机制。

Mt.r
|

有时候在思考 JS 是怎么处理路由的,nginx 配置是什么意思

https://router.vuejs.org/guide/essentials/history-mode.html

location / {
  try_files $uri $uri/ /index.html;
}

后来才明白,如果找不到资源就指向 index.thml 这个文件,这时候 js 读取了 url 路径,从而拿到正确的路由,真的很方便。

    root /data/www/vue;
    server {
        listen       80;
        server_name  localhost;

        location / {
            try_files $uri $uri/ /index.html;
        }

        location /app {
            try_files $uri $uri/ /app/index.html;
        }

        location /pc {
            try_files $uri $uri/ /pc/index.html;
        }

        location ^~ /b/ {
            proxy_pass http://1.1.1.1:80;
        }

        location ^~ /a/ {
            proxy_pass http://1.1.1.1:81;
        }

        location ^~ /c/ {
            proxy_pass http://1.1.1.1:82;
        }
    }

参考文章