Jachym
Jachym

Reputation: 23

Serve static files using html string in express.js

I do frontend so I am sometimes lost when I am trying to do something on server.

I have this server.js file

const express = require('express');
const http = require('http');
const path = require('path');
const logger = require('morgan');
const renderPage = require('./layout');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const admin = require("firebase-admin");

var index = require('./routes/index');

// Initialize the Express App
const app = express();

// Apply body Parser and server public assets and routes
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.resolve(__dirname, 'public')));


app.use('/', index);
app.use((req, res, next) => {
  res
    .set('Content-Type', 'text/html')
    .status(200)
    .end(renderPage());
});

var server = http.createServer(app);

// start app
server.listen(3000);

module.exports = app;

..and this string template

const renderPage = (initialState) => {
  return `
    <!DOCTYPE html>
    <html>
        <head>
            <link href="public/css/main.css"/>
            <script src="some external javascript"/>
        </head>
    <body>
        <div id="app"></div>
        <script>
          window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
        </script>

    </body>
</html>
`;
};

module.exports = renderPage;

When I start the server, it works, but css and script file do not work

Can you see what I am doing wrong?

Upvotes: 1

Views: 1124

Answers (1)

Luke Stoward
Luke Stoward

Reputation: 1540

Assuming your server.js file and your public directory exist at the same level, the path.resolve(__dirname, 'public') will build the full path to the public directory where all of your static resources should exist. When you reference these files inside your HTML pages you specify the path relative to the public directory.

<link href="css/main.css"/>

This should be enough to find the file. Assuming that file exists at ../public/css/main.css.

Upvotes: 1

Related Questions