node+express 服务配置vue-router history路由模式

简介: 导语:在vue、react等单页面应用中,路由可以为history模式,就像正常多页面网页地址一样,没有#hash标志,看起来更美观。这种模式充分利用 history.pushState API 来完成 URL 跳转而无须重新加载页面。

导语:在vue、react等单页面应用中,路由可以为history模式,就像正常多页面网页地址一样,没有#hash标志,看起来更美观。

这种模式充分利用 history.pushState API 来完成 URL 跳转而无须重新加载页面。

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

不过这种模式要玩好,还需要后台配置支持。因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问 http://oursite.com/user/id 就会返回 404,这就不好看了。

所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。

后端配置案例

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>

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 的 Express

  • 安装 npm install --save connect-history-api-fallback
  • 导入依赖 var history = require('connect-history-api-fallback');
  • 可以按如下使用

    var connect = require('connect');
    
    var app = connect()
      .use(history())
      .listen(3000);
  • 或者

    var express = require('express');
    
    var app = express();
    app.use(history());
  • Options

    history({
      index: '/default.html',
      rewrites: [
        { from: /\/soccer/, to: '/soccer.html'}
      ]
      or
      rewrites: [
        {
          from: /^\/libs\/.*$/,
          to: function(context) {
            return '/bower_components' + context.parsedUrl.pathname;
          }
        }
      ]
    })

    官方文档

相关文章
|
1月前
|
JavaScript
如何使用Vue的路由实现组件的懒加载和按需加载?
如何使用Vue的路由实现组件的懒加载和按需加载?
29 1
|
12天前
|
JavaScript
vue路由导航守卫(全局守卫、路由独享守卫、组件内守卫)
vue路由导航守卫(全局守卫、路由独享守卫、组件内守卫)
29 0
|
1月前
vue3配置路由报错Catch all routes (“*“) must now be defined using a param with a custom regexp.
vue3配置路由报错Catch all routes (“*“) must now be defined using a param with a custom regexp.
43 0
|
1月前
|
JavaScript
如何使用Vue异步组件技术实现路由懒加载?
如何使用Vue异步组件技术实现路由懒加载?
12 1
|
11天前
|
开发框架 JavaScript 中间件
node+express搭建服务器环境
node+express搭建服务器环境
node+express搭建服务器环境
|
7天前
|
开发框架 JavaScript 前端开发
【Node系列】Express 框架
Express.js 是一个基于 Node.js 平台的极简、灵活的 web 应用开发框架,提供一系列强大的特性来帮助你创建各种 web 和移动设备应用。
25 2
|
8天前
|
JavaScript
Vue 路由切换时页面刷新页面重新渲染
在Vue中,路由切换并不自动重新渲染页面,这可能导致传递参数到子组件时出现问题。使用`this.$route.replace(&#39;地址&#39;)`或`this.$route.push({name:&#39;地址&#39;,params:{key:value}})`进行跳转,但子组件不会响应变化。为解决此问题,需监听`$route`对象的变化,如图所示,通过`watch: {$route}`确保页面更新。
|
16天前
|
JavaScript 数据安全/隐私保护 UED
导航守卫(全局,组件,路由独享)都有什么作用导航守卫在 Vue Router 中扮演着重要的角色,不同类型的导航守卫有着不同的作用:1. **全局导航守卫**: - **作用**:
导航守卫(全局,组件,路由独享)都有什么作用导航守卫在 Vue Router 中扮演着重要的角色,不同类型的导航守卫有着不同的作用:1. **全局导航守卫**: - **作用**:
9 0
|
1月前
|
JavaScript
在vue中,如何实现SPA单页面应用的路由管理?
在vue中,如何实现SPA单页面应用的路由管理?
21 2