Node Express 使用单页应用程序提供动态和静态文件

Node Express serving dynamic and static files with a single page application

我正在构建一个单页应用程序,并将节点 (v7.7.1) 用于服务器,将 express 用于路由和构建 API。

我的前端被打包到一个名为 /client 的文件夹中(所以你所有的 JS,css,img 和 html 都在那里)。我的 API 有根 url /api.

任何其他非文件或 API 的查询都应发送 index.html。所以我尝试了以下方法:

app.use(express.static(path.join(__dirname, '../client')));
app.get('*', function (req, res, next) {
    if (req.originalUrl.indexOf('/api') !== -1) {
        return next()
    }
    if (/\/(\w|-)+\.\w{2,5}$/gmi.test(req.originalUrl)) {
            return res.sendFile(rss);
    }
    res.sendFile(path.join(__dirname, '../client/index.html')); 
});

上面给出了 mime 控制台中 css 和 js 文件的类型错误(可能还有图像,但无法判断,因为没有加载任何内容)。

浏览器控制台:

Refused to apply style from '/app-2432393bf1588983d4f6.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

非常感谢有关如何更好地执行此操作或如何解决问题的任何提示。

这样做

   function getRoutes(){
      const router = require('express').Router();
      router.get('/abc',function(req,res,next){
         //logic
      })
      router.post('/bcd',function(req,res,next){
        //logic
      })
      router.all('*',function(req,res,next){
         res.redirect('/');   
      })   //make sure this one is always at the last of all routes. 
      return router;
   }     
app.use('/',express.static(__dirname +'/client'))); // for static content
app.use('/api',getRoutes());

它可以通过更多方式处理。

如果对你有帮助请告诉我

我会做一些更像是:

app.use(express.static(path.normalize(__dirname, '../client'))); // This will serve index.html by default on the "/" route

app.get('/api/:func', (req, res, next) => { // Call this with "/api/save"
        console.log(`Called the API's ${req.params.func} function`);
        next()
    })
    .get("/file/:filename", (req,res) => res.sendFile(req.params.filename) ) // call "/file/style.css"

编辑 在 OP 评论后

1) What about sending all other traffic to index.html ? My frontend handles any page not founds and the sorts.

您可以进行重定向

app.get( "*", (req,res) => res.redirect("/") )

2) I had this before but then then for some reason that doesn't make sense to me, when I looked at the source of the file found for style.css it was my html page.

呃,不确定如何检查或调试...