代码之家  ›  专栏  ›  技术社区  ›  tbhaxor

通过提供VueJS构建服务快递.js

  •  1
  • tbhaxor  · 技术社区  · 8 年前

    我要为vue js服务 dist/

    以下是api调用

    1. s-file/发送/:id
    2. terms/get/:哪个

    我已经用python找到了一个解决方案 here . 我不知道如何在节点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());
            }
    
        }
    })
    
    1 回复  |  直到 7 年前
        1
  •  14
  •   Benno    6 年前

    看一看 connect-history-api-fallback vue docs .

    使用连接历史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 
    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!');
    });
    
        2
  •  3
  •   tbhaxor    6 年前

    只需将此添加到所有有效路由的下面和上面 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'));
    
    推荐文章