vue路由history模式下打包node服务器配置

  vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。

  如果不想要很丑的 hash,我们可以用路由的 history 模式,这种模式充分利用 history.pushState API 来完成 URL 跳转而无须重新加载页面。

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

  当你使用 history 模式时,URL 就像正常的 url,例如 http://yoursite.com/user/id,也好看!

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

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

 

以下为nodejs的后台配置:

  本人当前项目结构为:

  

  其中server为打包之后创建的新文件:

// server.js

const http = require('http')
const fs = require('fs')
const httpPort = 8090

http.createServer((req, res) => {
  if (req.url.startsWith('/static/css') || req.url.startsWith('/static/js')) {
    fs.readFile('.' + req.url, (err, data) => {
      res.end(data);
      return;
    })
  }
  fs.readFile('index.html', '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)
})

在dist目录下,开启当前的node服务(node server.js),然后访问 localhost:8090 即可访问,然后在路由的任何页面刷新,都不会出现404,这样就完美解决了

 

转载于:https://www.cnblogs.com/xiaoyaoxingchen/p/10588734.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将 Vue 的哈希由(hash mode)改为 history 由(history mode),可以按照以下步骤进行操作: 1. 首先,确保您的项目已经安装了 Vue Router。如果尚未安装,可以使用以下命令进行安装: ```bash npm install vue-router ``` 2. 在项目的主入口文件(一般是 `main.js`)中导入 Vue Router,并创建一个由实例: ```javascript import Vue from 'vue'; import VueRouter from 'vue-router'; import App from './App.vue'; Vue.use(VueRouter); const router = new VueRouter({ mode: 'history', // 设置为 history 模式 routes: [ // 定义由 // ... ], }); new Vue({ render: (h) => h(App), router, // 将由实例添加到根组件中 }).$mount('#app'); ``` 注意,这里的关键是将 `mode` 设置为 `'history'`。 3. 在服务器端进行配置,以确保在使用 history 由时能够正确处理由请求。这是因为在 history 模式下,直接访问某个径时,服务器需要返回对应的页面。例如,在使用 Node.js/Express 作为服务器时,可以添加如下配置: ```javascript const express = require('express'); const path = require('path'); const app = express(); app.use(express.static(path.join(__dirname, 'dist'))); // 处理所有由请求,返回 index.html app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'dist', 'index.html')); }); app.listen(3000, () => { console.log('Server started on port 3000'); }); ``` 这样,当用户直接访问某个径时,服务器会返回 `index.html`,然后在客户端由 Vue Router 接管由的处理。 4. 最后,根据您的需求,使用 Vue Router 的由功能进行定义和使用由。 这样,您就成功将 Vue 的哈希由改为了 history 由。记得在切换由时,不再出现 `#` 符号,URL 更加美观。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值