YT98
YT98

Reputation: 111

Express static css not served

I have been trying to figure this out for hours and my head is about to explode. I really hope it's not some stupid little detail I missed...

I have a server-side rendering react application set-up. Everything is going fine. The only problem I have is that I can't seem to get the css to load.

Here is my file tree (without node_modules): https://i.sstatic.net/xevUb.png'

I have the following code in my server.js file

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

And this is my template.js file :

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>
  `;
};

When I go on my local server. I get the html delivered and the bootstrap styles are applied to it. However, I get a 400 bad request error for the style.css and client.js linked in my template.js file.

I really hope someone can help me out on this one...

EDIT

Here is what I see on the developer console : Developer console screenshot

Upvotes: 2

Views: 2922

Answers (1)

idbehold
idbehold

Reputation: 17168

Your server.js file appears to be inside your dist folder, which means that __dirname would be ./dist instead of ./ like your code seems to be written. What you need to do is something like this:

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

Upvotes: 3

Related Questions