2017-03-09 32 views
2

我一直在试图弄清楚这几个小时,我的头即将爆炸。我真的希望这不是一些愚蠢的小细节,我错过了...快递静态CSS没有送达

我有一个服务器端渲染反应应用程序设置。一切都很顺利。我唯一的问题是,我似乎无法获得加载的CSS。

这里是我的目录树(不node_modules):https://i.stack.imgur.com/xevUb.png

我有下面的代码在我server.js文件

app.use('static', express.static(__dirname + '/public')); 
 
app.use('dist', express.static(__dirname + '/dist')); 
 

 
app.get('*', (req, res) => { 
 
     match({ 
 
      routes, 
 
      location: req.url 
 
     }, (error, redirectLocation, renderProps) => { 
 
      if (error) { 
 
      res.status(500).send(error.message) 
 
      } else if (redirectLocation) { 
 
      res.redirect(302, redirectLocation.pathname + redirectLocation.search) 
 
      } else if (renderProps) { 
 
      var html = renderToString(< RouterContext { ...renderProps 
 
       } 
 
       />); 
 
       res.status(200).send(template({ 
 
       body: html 
 
       })); 
 
      } 
 
      else { 
 
       res.status(400).send('Not found.') 
 
      } 
 
      }); 
 
     });

这是我的模板。 js文件:

export default ({ body }) => { 
 
    return ` 
 
    <!DOCTYPE html> 
 
    <html> 
 
     <head> 
 
     <title>test</title> 
 
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> 
 
     <link rel="stylesheet" href="/static/css/style.css" /> 
 
     </head> 
 

 
     <body> 
 
     <div id="root">${body}</div> 
 
     </body> 
 

 
     <script src="dist/client.js"></script> 
 
    </html> 
 
    `; 
 
};

当我在我的本地服务器上。我得到的HTML传递和引导样式应用到它。但是,我的template.js文件中链接的style.css和client.js出现了400错误的请求错误。

我真的希望有人能帮助我在这一个...

编辑

这是我看到开发者控制台上: Developer console screenshot

回答

2

server.js文件似乎在您的dist文件夹内,这意味着__dirname将是./dist而不是./就像你的代码似乎写了一样。你需要做的是这样的:

const path = require('path') 
const projectRoot = path.resolve(__dirname, '../') 
app.use('static', express.static(projectRoot + '/public')) 
app.use('dist', express.static(__dirname)) 
+0

是的,我认为就是这样。我改变了这一点,client.js文件现在正在服务。仍然没有CSS虽然:( – YT98

+0

我把style.css放在dist目录中,它现在的作品。我不明白为什么公共目录没有正确服务。 – YT98

+0

你可以'console.log(path.resolve (__dirname,'../'))'在你的server.js中?它应该指向你的项目的根目录。 – idbehold