【问题标题】:Express static css not served快递静态 css 未提供服务
【发布时间】:2017-07-30 01:42:56
【问题描述】:

我已经尝试解决这个问题好几个小时了,我的脑袋快要爆炸了。我真的希望这不是我错过的一些愚蠢的小细节......

我有一个服务器端渲染反应应用程序设置。一切都很顺利。我唯一的问题是我似乎无法加载 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.')
            }
          });
      });

这是我的 template.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 bad request 错误。

我真的希望有人可以帮助我解决这个问题......

编辑

这是我在开发者控制台上看到的:

【问题讨论】:

    标签: node.js reactjs express server-side-rendering


    【解决方案1】:

    您的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))
    

    【讨论】:

    • 是的,我想就是这样。我对此进行了更改,现在正在提供 client.js 文件。虽然仍然没有css :(
    • 我将 style.css 放在 dist 目录中,现在可以使用了。我不明白为什么公共目录没有正确提供。
    • 你能在你的 server.js 中 console.log(path.resolve(__dirname, '../')) 吗?它应该指向你项目的根目录。
    猜你喜欢
    • 2010-12-01
    • 2018-03-23
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 2020-02-21
    • 1970-01-01
    • 2014-03-16
    相关资源
    最近更新 更多