使用历史模式通过 Express.js 为 VueJS 构建提供服务 [英] Serving VueJS Builds via Express.js using history mode
本文介绍了使用历史模式通过 Express.js 为 VueJS 构建提供服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过 express js 为 vue js dist/
提供服务.我在 vue js 应用程序中使用历史路由器.
I want to serve vue js dist/
via express js. I am using history router in vue js app.
以下是api调用
- api/
- s-file/sending/:id
- terms/get/:which
因为我在 python 中找到了解决方案这里.我不知道如何在 node js 中使用 express
As i have figured out a solution in python here. I don't know how to do it in node js with express
我现在使用的代码是
app.use(function (req, res, next) {
if (/api/.test(req.url))
next();
else {
var file = "";
if (req.url.endsWith(".js")) {
file = path.resolve(path.join(distPath, req.url))
res.header("Content-Type", "application/javascript; charset=utf-8");
res.status(200);
res.send(fs.readFileSync(file).toString());
} else if (req.url.endsWith(".css")) {
file = path.resolve(path.join(distPath, req.url))
res.header("Content-Type", "text/css; charset=utf-8");
res.status(200);
res.send(fs.readFileSync(file).toString());
} else {
file = path.resolve(path.join(distPath, "index.html"))
res.header("Content-Type", "text/html; charset=utf-8");
res.status(200);
res.send(fs.readFileSync(file).toString());
}
}
})
推荐答案
看看 connect-history-api-fallback"nofollow noreferrer">vue 文档.这应该可以解决您的问题.
Have a look at connect-history-api-fallback that is referenced in the vue docs. This should solve your problems.
使用 connect-history-api-fallback 的示例
var express = require('express');
var history = require('connect-history-api-fallback');
var app = express();
// Middleware for serving '/dist' directory
const staticFileMiddleware = express.static('dist');
// 1st call for unredirected requests
app.use(staticFileMiddleware);
// Support history api
// this is the HTTP request path not the path on disk
app.use(history({
index: '/index.html'
}));
// 2nd call for redirected requests
app.use(staticFileMiddleware);
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
这篇关于使用历史模式通过 Express.js 为 VueJS 构建提供服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文