1

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?

1
  • You don't need to specify the public segment of the href. css/main.css should be enough. Commented Dec 13, 2017 at 15:39

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

great!!! that feeling when you have headaches because of such simple thing.
Are you happy with my explantation? i.e. does it make sense and you understand why you encountered the problem?
yes, very much. The explanation couldn't be better. It is actually good, that I asked for such a simple problem, cause if I would incidentally solved it, I would have never understand where the problem was

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.