vue路由的两种模式配置以及history模式下面后端如何配置

1、hash ——即地址栏URL中的#符号。
hash 虽然出现URL中,但不会被包含在HTTP请求中,对后端完全没有影响,因此改变hash不会重新加载页面。
2、history ——利用了HTML5 History Interface 中新增的pushState() 和replaceState() 方法。需要特定浏览器支持
history模式,会出现404 的情况,需要后台配置。
3、hash模式下,仅hash符号之前的内容会被包含在请求中,如 http://www.baidu.com, 因此对于后端来说,即使没有做到对路由的全覆盖,也不会返回404错误;
history模式下,前端的url必须和实际向后端发起请求的url 一致,如http://www.baidu.com/a/ 。如果后端缺少对/a 的路由处理,将返回404错误。

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

history模式下配置nginx

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

history模式下配置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>

history模式下配置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)
})

猜你喜欢

转载自blog.csdn.net/chendongpu/article/details/106158431