通过 Express 为 VueJS 构建提供服务.js使用历史记录模式



我想通过Express js提供vue jsdist/。我在 vue js 应用程序中使用历史路由器。

以下是 API 调用

  1. 应用程序接口/
  2. s-file/sending/:id
  3. terms/get/:哪

正如我在这里想出 python 的解决方案一样。我不知道如何在节点js中使用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());
}
}
})

看看 vue 文档中引用的连接历史 api-fallback。 这应该可以解决您的问题。

使用连接历史记录 API 回退的示例

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!');
});

如果有人想使用,那就更简单了

只需在所有有效路线下方和上方添加此app.listen

app.all("*", (_req, res) => {
try {
res.sendFile('/absolute/path/to/index.html');
} catch (error) {
res.json({ success: false, message: "Something went wrong" });
}
});

确保您已包含

app.use(express.static('/path/to/dist/directory'));

最新更新