Vue应用部署到服务器由于路由的history模式下刷新当前路由出现404的问题

用于默认模式vue-router散模式 -它使用URL的哈希来模拟一个完整的URL,这样的页面不会被重新加载的URL发生变化时。

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

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

 

使用历史记录模式时,URL将显示为“正常”,例如http://oursite.com/user/id

但是出现了一个问题:由于我们的应用程序是单页客户端应用程序,如果没有正确的服务器配置,如果用户http://oursite.com/user/id直接在浏览器中访问,则会收到404错误。现在那很难看。

不用担心:要解决此问题,您需要做的就是向服务器添加一个简单的全部回退路由。如果网址与任何静态资源都不匹配,则该网址应与index.html您的应用所在的网页相同。

示例服务器配置

Apache

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

而不是mod_rewrite,你也可以使用。FallbackResource

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)
})

表达Node.js

对于Node.js / Express,请考虑使用connect-history-api-fallback中间件

Internet信息服务(IIS)

  1. 安装IIS UrlRewrite
  2. web.config使用以下内容在站点的根目录中创建文件:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Handle History Mode and custom 404/500" stopProcessing="true">
          <match url="(.*)" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

Caddy

rewrite {
    regexp .*
    to {path} /
}

Firebase hosting

将此添加到您的firebase.json

{
  "hosting": {
    "public": "dist",
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

注意

有一点需要注意:您的服务器将不再报告404错误,因为所有未找到的路径现在都会提供您的index.html文件。要解决此问题,您应该在Vue应用程序中实现一个全能路径以显示404页面:

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '*', component: NotFoundComponent }
  ]
})

或者,如果您使用的是Node.js服务器,则可以通过使用服务器端的路由器来匹配传入的URL来实现回退,如果没有匹配的路由,则使用404进行响应。有关更多信息,请查看Vue服务器端呈现文档

 

参考文档:https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue 路由history 模式下,刷新页面会导致 404 错误的出现,这是因为浏览器会向服务器发送请求,但服务器并没有对应的路由,因此就会返回 404 错误。解决这个问题的方法有两种: 1. 配置后端服务器 如果你的 Vue 项目部署在 Apache 或 Nginx 等 Web 服务器上,你可以配置服务器来处理这个问题。具体做法是,在服务器上配置一个重定向规则,将所有的 URL 请求都重定向到 index.html 文件上。以 Apache 服务器为例,可以在 Apache 的配置文件(如 httpd.conf)中添加以下规则: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule> ``` 这个配置将所有的 URL 请求都重定向到 index.html 文件上,这样即使刷新页面,服务器也会返回正确的内容。 2. 使用 hash 模式 如果你不想在服务器上配置重定向规则,你可以考虑使用 hash 模式。在 hash 模式下,Vue 会使用 URL 中的 # 符号来表示路由,这样即使刷新页面,浏览器也只会重新加载 index.html 文件,而不会向服务器发送请求。要启用 hash 模式,只需要在 Vue 路由的配置中添加以下代码: ``` const router = new VueRouter({ mode: 'hash', routes: [...] }) ``` 这样就可以启用 hash 模式了。需要注意的是,hash 模式下,URL 中的 # 符号后面的内容不会被发送到服务器,因此你需要在前端代码中使用 JavaScript 来解析 URL 中的 hash 值,并根据这个值来渲染不同的页面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YuanlongWang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值