【问题标题】:vue.js routing issue in apacheapache中的vue.js路由问题
【发布时间】:2017-10-25 15:51:12
【问题描述】:

我有一个带有 vue 路由器的 vue.js 应用程序来渲染各种组件。我有一个路径 /home 加载 home 组件。在开发环境中,我可以通过在地址栏中输入localhost:8080/home 以及使用<router-link> 设置链接来访问组件。当我将生产版本部署到 apache 服务器时,当我给 localhost/home 时给出错误

在此服务器上找不到请求的 URL /home。

但是链接可以正常工作,当我们点击链接时地址栏中会显示localhost/home 为什么会发生这种情况?如何解决?

【问题讨论】:

    标签: apache vue-router


    【解决方案1】:

    直接来自 Vue 路由器网站。

    vue-router 的默认模式是散列模式——它使用 URL 散列来 模拟一个完整的 URL,以便在 URL 时不会重新加载页面 变化。

    为了摆脱散列,我们可以使用路由器的历史模式,它 利用 history.pushState API 实现 URL 导航,无需 页面重新加载:

    const router = new VueRouter({ mode: 'history', routes: [...] }) 使用历史模式时,URL 看起来“正常”,例如 http://oursite.com/user/id。漂亮!

    不过,问题来了:由于我们的应用是单页客户端 端应用程序,如果没有适当的服务器配置,用户将获得 如果他们直接访问http://oursite.com/user/id,则会出现 404 错误 浏览器。现在这很难看。

    不用担心:要解决此问题,您只需添加一个简单的 到您的服务器的全部后备路由。如果 URL 不匹配任何 静态资产,它应该提供与您的应用相同的 index.html 页面 住在里面。美丽,再次!

    阿帕奇

    <IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteBase /
      RewriteRule ^index\.html$ - [L]
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . /index.html [L]
    </IfModule>
    

    nginx

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

    本机 Node.js

    const http = require('http')
    const fs = require('fs')
    const httpPort = 80
    
    http.createServer((req, res) => {
      fs.readFile('index.htm', 'utf-8', (err, content) => {
        if (err) {
          console.log('We cannot open "index.htm" file.')
        }
    
        res.writeHead(200, {
          'Content-Type': 'text/html; charset=utf-8'
        })
    
        res.end(content)
      })
    }).listen(httpPort, () => {
      console.log('Server listening on: http://localhost:%s', httpPort)
    })
    

    [0]https://router.vuejs.org/en/essentials/history-mode.html

    【讨论】:

      【解决方案2】:

      在路由器实例中,我使用了历史模式,它给出了一个不带哈希 (#) 的 URL。我将模式形式“历史”更改为默认的“哈希”,它为我解决了问题。

      【讨论】:

      • 您能否详细说明您的解决方案?
      猜你喜欢
      • 2020-03-05
      • 2017-10-28
      • 2015-12-23
      • 2020-03-14
      • 1970-01-01
      • 2014-08-03
      • 2017-09-24
      • 2019-04-15
      • 1970-01-01
      相关资源
      最近更新 更多