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

3

我正在构建一个单页应用,使用node(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.

任何关于如何更好地完成此操作或如何修复问题的提示都将不胜感激。
2个回答

2
我会更倾向于这样做:
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"

编辑 根据原帖评论

1)将所有其他流量发送到index.html怎么样?我的前端会处理任何未找到的页面等。

您可以进行重定向。

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

2) 我之前遇到过这个问题,但是出现的原因对我来说毫无意义,当我查看style.css文件的源代码时,发现它是我的html页面。

嗯,不确定如何检查或调试这个问题...


谢谢。1)其他流量发送到index.html怎么样?我的前端处理任何未找到的页面和排序。2)我以前有过这个问题,但是出于某些原因,当我查看style.css文件的源代码时,它是我的html页面。 - denislexic

1

按照这种方式执行

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

它可以用许多更多的方式处理。

如果有帮助,请告诉我。


但是,yourAPIRouting 究竟是什么? - Jeremy Thille
1
任何返回 Router 函数的 Express 中间件,可以在其中定义其他路由。@JeremyThille - Saikat Hajra
@SaikatHajra 谢谢。如果只有一个页面,发送任何其他路径的HTML文件怎么办? - denislexic
就像我的index.html处理404状态和/home/about/...一样。 - denislexic
如果您在问题中添加更多内容,将有助于回答您。 - Saikat Hajra
我在前端使用 React 处理所有路由,因此是一个 单页应用程序 - denislexic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接