Serving VueJS Builds via Express.js using history mode

前端 未结 2 1045
囚心锁ツ
囚心锁ツ 2020-12-05 16:59

I want to serve vue js dist/ via express js. I am using history router in vue js app.

The following are the api calls

  1. api/
  2. s-file
相关标签:
2条回答
  • 2020-12-05 17:27

    The very simpler one if anyone wants to use

    Just add this below all the valid routes and above app.listen

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

    Make sure you have included

    app.use(express.static('/path/to/dist/directory'));
    
    0 讨论(0)
  • 2020-12-05 17:29

    Have a look at connect-history-api-fallback that is referenced in the vue docs. This should solve your problems.

    Example using 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!');
    });
    
    0 讨论(0)
提交回复
热议问题