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

问题描述 投票:3回答:1

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

以下是api调用

  1. api /
  2. s文件/发送/:id
  3. 条款/获取/:哪个

正如我已经找到了python here中的解决方案。我不知道如何在express

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

    }
})
node.js express vue.js
1个回答
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!');
});

Update 1:添加了示例

更新2:将示例更改为正确的用法(https://github.com/bripkens/connect-history-api-fallback/tree/master/examples/static-files-and-index-rewrite

我错过了历史部分,我很糟糕。看看connect-history-api-fallback中引用的vue docs。这应该可以解决您的问题吗?

更新示例

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!');
});
© www.soinside.com 2019 - 2024. All rights reserved.