【问题标题】:Serving VueJS Builds via Express.js using history mode使用历史模式通过 Express.js 服务 VueJS 构建
【发布时间】:2019-02-18 23:33:57
【问题描述】:

我想通过 express js 服务于 vue js dist/。我在 vue js 应用程序中使用历史路由器。

以下是api调用

  1. api/
  2. s-file/sending/:id
  3. terms/get/:which

正如我在 python here 中找到的解决方案一样。我不知道如何在带有express的node js中做到这一点

我现在使用的代码是

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());
        }

    }
})

【问题讨论】:

  • 我不清楚你的要求,是 api/ 是一个 rest api 还是有任何静态文件目录等。?
  • 所有提到的端点都是 REST API

标签: node.js express vue.js


【解决方案1】:

查看vue docs 中引用的connect-history-api-fallback。 这应该可以解决您的问题。

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

【讨论】:

  • 它不适用于 vue routerlinks,即后备,而且我得到Cannot GET /
  • 我的错,看看我更新的答案中connect-history-api-fallback的用法
  • 错误:禁止您的客户端在部署到 docker 后无权从该服务器获取 URL /!这是什么意思?
  • @LOG_TAG 此错误可能在您的主机配置或服务器代码中有很多原因。考虑打开一个单独的问题,在其中提供所需的所有背景信息:(您要做什么?什么有效?什么无效?到目前为止您尝试了什么)
  • @Benno 肯定感谢您的回复,我正在使用通过 gcloud 运行的 google cloud 处理相同的“通过 Express.js 服务 VueJS 构建”!想知道它会重复一个 :)
【解决方案2】:

如果有人想使用的话,这个非常简单

只需在所有有效路线下方和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'));

【讨论】:

  • 为什么函数中没有使用“await”时会出现“async”?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-11
  • 1970-01-01
  • 2021-02-04
  • 1970-01-01
  • 2018-12-26
  • 2020-01-27
  • 2018-05-20
相关资源
最近更新 更多