Gur*_*ngh 3 node.js express vue.js
我想dist/通过express js 服务vue js。我正在vue js应用程序中使用历史记录路由器。
以下是api调用
正如我在这里找到 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());
}
}
})
Run Code Online (Sandbox Code Playgroud)
如果有人想使用的话,这是非常简单的
只需将其添加到所有有效路线的下方和上方app.listen
app.all("*", (_req, res) => {
try {
res.sendFile('/absolute/path/to/index.html');
} catch (error) {
res.json({ success: false, message: "Something went wrong" });
}
});
Run Code Online (Sandbox Code Playgroud)
确保您已包含
app.use(express.static('/path/to/dist/directory'));
Run Code Online (Sandbox Code Playgroud)
小智 6
原始答案
您可以使用express.static()服务目录中的所有文件。您的API路由应单独处理。
例:
var express = require('express');
var app = express();
// Serve all the files in '/dist' directory
app.use(express.static('dist'));
// Handle a get request to an api route
app.get('/your-api-route/:id', function (req, res) {
// You can retrieve the :id parameter via 'req.params.id'
res.send(`Did GET /your-api-route/${req.params.id}!`);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Run Code Online (Sandbox Code Playgroud)
更新1:添加了示例
更新2:将示例更改为正确用法(https://github.com/bripkens/connect-history-api-fallback/tree/master/examples/static-files-and-index-rewrite)
我错过了历史部分,我很糟糕。看看vue docs中引用的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
app.use(history({
index: '/dist/index.html'
}));
// 2nd call for redirected requests
app.use(staticFileMiddleware);
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3386 次 |
| 最近记录: |