vue使用 history 路由模式后端配置【java、node】

1.后端SpringBoot如何配置:

当我们使用Vue开发时,一般会用到vue-router来作为前端路由,实现单页应用。vue-router提供了两种模式模拟一个完整的 URL:hash模式和history模式。

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

//查看id为1的文章
http://localhost:8888/#/view/1

history模式:URL 就像正常的 url,比较好看。

//查看id为1的文章
http://localhost:8888/view/1


vue-router默认是使用hash模式的,不需要额外的配置,如果我们想使用history模式该如何配置呢?

1 前端:vue-router的mode: ‘history’

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


2 后端:我是使用SpringBoot,要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。详细看vue-router的官方文档。

SpringBoot默认匹配不到URL时,会返回一个默认的页面,所以可以配置一下默认的配置Bean。

@SpringBootApplication
public class BlogApiApplication {
 
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(BlogApiApplication.class);
        app.run(args);
    }
 
 
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
 
        return new EmbeddedServletContainerCustomizer() {
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
 
                ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
 
                container.addErrorPages(error404Page);
            }
        };
    }
}
 

3.node配置

1.  新建server-proxy.js文件(dev和pro公用的proxy转发文件)

var proxy = {
  local:"http://localhost:9999",//mock环境
}
var config = {
  dev: {
      historyApiFallback: true,
      stats: { colors: true },
      hot: true,
      inline: true,
      progress: true,
      disableHostCheck:true,
      //contentBase:"./app/index",
      proxy: {
          '/api/mock': {
            target: proxy.local, //pathRewrite: {'^/column' : '/column'},                
              secure: false,
              changeOrigin: true
          }
      }
  },
  portPro: '10086' 

}
module.exports = config;

2.  新建 server-after-package.js ,打包后在当前目录就可以启动history模式,并做了proxy的转发。

console.time('start server-after-package need time')
const http = require('http')
const fs = require('fs')
var proxyhttp = require('express-http-proxy')
var express = require('express')
var app = express()
var proxy = require('./server-proxy')
app.set('roots', __dirname+'/dist')
app.use('/', express.static(app.get('roots')))
app.engine('html', require('ejs').renderFile)
for (var i in proxy.dev.proxy) {
    if (proxy.dev.proxy.hasOwnProperty(i)) {
        console.log(i, proxy.dev.proxy[i].target)
        app.use(i + '/*', proxyhttp(proxy.dev.proxy[i].target, {
            proxyReqPathResolver: function (req, res) {
                console.log(req.originalUrl)
                return req.originalUrl
            }
        }))
    }
}
app.use('*', function (req, res, next) {
  fs.readFile(app.get('roots')+'/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)
  })
});
var server = app.listen(proxy.portPro, function () {
    var host = server.address().address
    var port = server.address().port
    console.log('app listening at ' + require("os").hostname() + ' http://localhost:' + port)
    console.timeEnd('start server-after-package need time')
})

 问题:

报错:“Uncaught SyntaxError: Unexpected token <” 时,首先查看路径设置是否正确(主要时script指向的src是否正确,是否能访问)

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值