简体   繁体   English

Node Express通过单个页面应用程序提供动态和静态文件

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

I'm building a single page application and using node (v7.7.1) for server and express for routing and building the API. 我正在构建一个单页应用程序,并将节点(v7.7.1)用于服务器,并表达用于路由和构建API。

My frontend is packaged into a folder called /client (so all you JS, css, img and html are there). 我的前端被打包到一个名为/client的文件夹中(因此所有JS,css,img和html都在那里)。 And my API has for root url /api . 而且我的API的根网址为/api

Any other queries that are not files or API should be sent the index.html . 不是文件或API的任何其他查询都应该发送给index.html So I tried the following: 所以我尝试了以下方法:

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')); 
});

The above is giving me errors for mime type error in console for css and js files (maybe images as well, but can't tell since nothing loads). 上面给了我关于css和js文件的控制台中的mime类型错误的错误(也许还有图像,但是由于没有加载而无法分辨)。

Browser console: 浏览器控制台:

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.

Any tips on how to do this better or how to fix issue much appreciated. 任何有关如何更好地做到这一点或如何解决问题的技巧都值得赞赏。

do it like this way 这样做

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

it can be handled in many more ways. 它可以通过更多方式处理。

let me know if it helps you 让我知道这是否对您有帮助

I would do something more like : 我会做更多类似的事情:

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"

EDIT after OP's comments OP评论后编辑

1) What about sending all other traffic to index.html ? 1)将所有其他流量发送到index.html怎么样? My frontend handles any page not founds and the sorts. 我的前端处理所有未找到和排序的页面。

You can do a redirection 您可以进行重定向

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. 2)我以前有这个,但是后来由于某种对我来说没有意义的原因,当我查看为style.css找到的文件的源代码时,它就是我的html页面。

Uh, not sure how to check or debug that... 嗯,不确定如何检查或调试...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM