配置一个可以使用Vue的History模式的后端服务

因为大部分情况下都是使用hash模式,因此很少关心History的使用。

最近再次意识熟悉后端才能全面理解项目,于是开始一些相关性研究。下面是History后端服务代码,使用了express框架。使用了ejs模板引擎解析HTML文件。

const http = require('http');
const path = require('path');
var ejs = require('ejs');  //我是新引入的ejs插件

const express = require('express');
const app = express();
// 添加中间件,设置从`dist`文件夹中查找文件
app.use(express.static(path.join(__dirname, 'dist')));
app.set('views', './dist') // specify the views directory
app.engine('html', ejs.__express);

app.set('view engine', 'html') // register the template engine

app.use('*',(request, response) => {
    // 这里最后没有调用next扔给下一个中间件,而是直接输出了响应内容
    response.render('index');
});
// 最后,创建server,并且输出地址
const server = http.createServer(app);
server.listen(3000, () => {
    console.log('Listening on %j', server.address());
});

 当然还可以使用nginx作为服务端。配置如下

nginx作为Vue单页面项目后端服务
 server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;  
        }
………………

  

原文地址:https://www.cnblogs.com/zhensg123/p/13045431.html