zoukankan      html  css  js  c++  java
  • Vue 部署单页应用,刷新页面 404/502 报错

    在 Vue 项目中,可以选择 hash或者 history.pushState() 实现路由跳转。如果在路由中使用history模式:

    export default new Router({
      mode: 'history',
    
      base: __dirname,
      scrollBehavior,
      routes: [index, blog, project, about, list]
    })
    

    那么,当我们 npm run build 完成并部署到服务器后,刷新某个路由下的页面,会出现 404 或者 502 错误。

    这是因为刷新页面时访问的资源在服务端找不到,因为vue-router设置的路径不是真实存在的路径。

    解决方法

    简单配置下 nginx ,让所有路由(url)下的页面重写到 index.html即可:

    
    server {
            listen 80;
            server_name www.fayinme.cn;
    
            gzip on;
            gzip_min_length 1k;
            gzip_buffers 4 16k;
            gzip_comp_level 2;
            gzip_vary off;
            gzip_disabled "MSIE [1-6]";
            autoindex on;
    
            root /www/blogfront/production/current;
            index index.html;
            
            location / {
                    try_files $uri $uri/ @router;
                    index index.html;
            }
    
            location @router {
                    rewrite ^.*$ /index.html last;
            }
    
    

    注意

    配置完成后,如果刷新任意页面(F5)都跳转到首页,你需要查看下 app.vue 是否包含了如下代码:

      created() {
        this.$router.push('/')
      }
    

    如果有,注释或删除即可。

  • 相关阅读:
    The Castle
    洛谷七月月赛
    Superprime Rib
    Leetcode 记录(201~300)
    03爬虫 爬取hfutxc成绩
    Leetcode 记录(101~200)
    LeetCode Weekly Contest 32
    Leetcode 记录(1~100)
    C++,java信息,文件传输
    毕业设计-自然场景下显著目标的检测
  • 原文地址:https://www.cnblogs.com/fayin/p/7221619.html
Copyright © 2011-2022 走看看