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

我有一个服务器端渲染反应应用程序设置。一切都很好。我唯一的问题是我似乎无法加载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错误的请求错误。

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

编辑

这是我在开发人员控制台上看到的内容:
node.js - 表示不提供静态CSS-LMLPHP

最佳答案

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

10-05 20:43
查看更多