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

原文连接:https://www.cnblogs.com/mica/p/10876822.html
一、hash ——即地址栏URL中的#符号。
hash 虽然出现URL中,但不会被包含在HTTP请求中,对后端彻底没有影响,所以改变hash不会从新加载页面。
二、history ——利用了HTML5 History Interface 中新增的pushState() 和replaceState() 方法。须要特定浏览器支持
history模式,会出现404 的状况,须要后台配置。
三、hash模式下,仅hash符号以前的内容会被包含在请求中,如 http://www.baidu.com, 所以对于后端来讲,即便没有作到对路由的全覆盖,也不会返回404错误;
history模式下,前端的url必须和实际向后端发起请求的url 一致,如http://www.baidu.com/a/ 。若是后端缺乏对/a 的路由处理,将返回404错误。html

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

history模式下配置nginx前端

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

history模式下配置Apachenginx

<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)
})
相关文章
相关标签/搜索