0

So whats happening is I have a reactjs project that has react router. So when I try and hit /dashboard/stream it's getting the index.html off the server but then the css and js are getting 301 errors and it's not displaying anything.

express server

const express = require('express');
const {
  createServer
} = require('http');
const io = require('socket.io');
const haiku = require('./haiku');

const app = express();
const server = createServer(app);
const userIds = {};
const noop = () => {};

app.use('/*', express.static(`${process.cwd()}/../client`));

/**
 * Random ID until the ID is not in use
 */
function randomID(callback) {
  const id = haiku();
  if (id in userIds) setTimeout(() => haiku(callback), 5);
  else callback(id);
}

/**
 * Send data to friend
 */
function sendTo(to, done, fail) {
  const receiver = userIds[to];
  if (receiver) {
    const next = typeof done === 'function' ? done : noop;
    next(receiver);
  } else {
    const next = typeof fail === 'function' ? fail : noop;
    next();
  }
}

/**
 * Initialize when a connection is made
 * @param {SocketIO.Socket} socket
 */
function initSocket(socket) {
  let id;
  socket
    .on('init', () => {
      randomID((_id) => {
        id = _id;
        userIds[id] = socket;
        socket.emit('init', {
          id
        });
      });
    })
    .on('request', (data) => {
      sendTo(data.to, to => to.emit('request', {
        from: id
      }));
    })
    .on('call', (data) => {
      sendTo(
        data.to,
        to => to.emit('call', { ...data,
          from: id
        }),
        () => socket.emit('failed')
      );
    })
    .on('end', (data) => {
      sendTo(data.to, to => to.emit('end'));
    })
    .on('disconnect', () => {
      delete userIds[id];
      console.log(id, 'disconnected');
    });

  return socket;
}

module.exports.run = (config) => {
  server.listen(config.PORT);
  console.log(`Server is listening at :${config.PORT}`);
  io.listen(server, {
      log: true
    })
    .on('connection', initSocket);
};

index.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, user-scalable=no" />
  <link href="/dist/css/app.min.css" rel="stylesheet">
</head>

<body>
  <div id="root"></div>
  <script type="text/javascript" src="/dist/js/app.min.js"></script>
</body>

</html>

how come my index.html is loaded but then the js and css isnt.

folder structure is this:

server ... client dist css js index.html ...

To me I can't see if it's loading that index.html file how it can't load the css and js that are linked to it.

8
  • is the dist folder inside the client folder? Commented Aug 7, 2018 at 13:39
  • it is not about express , express does not handle Frontend , be sure that path is true , open "view page source" and click on css and js files , check that , it is 404 or not , also you can test this path : "./dist/js/app.min.js" Commented Aug 7, 2018 at 13:44
  • @peetya yes dist is in the client folder as that is where webpack builds it Commented Aug 7, 2018 at 13:46
  • @Nimahabibkhoda I still get a 301 error when i do that. Commented Aug 7, 2018 at 13:47
  • Check the Network tab in the chrome developer tools that what is the route of the static files and copy them here please. Commented Aug 7, 2018 at 13:55

2 Answers 2

2

The problem is that you are using absolute path for the static files because they start with a / so if the url is /dashboard/stream then it will tries to load the css and js file from /dashboard/dist/....

To fix it remove the / from the beginning of the path to have a relative path.

<link href="dist/css/app.min.css" rel="stylesheet">

and

<script type="text/javascript" src="dist/js/app.min.js"></script>
Sign up to request clarification or add additional context in comments.

3 Comments

it needs to load them from localhost:5000/dist/js/app.min.js as localhost:5000/dashboard/stream is a js route not a physical route
are you using react-router for the routing, or something on the backend?
react router for routing on the frontend nothing on the backend
0

This does the trick with Angular so why not with React considering that you are using front-end routing:

  1. Use an absolute path in your server.js file:

    app.use('/public', express.static(path.join(__dirname, '../client/dist')));

  2. Serve your front-end routes in your server.js file:

    app.get('*', function(req, res, next) { res.sendFile("../client/index.html", { root: __dirname }); });

Now you should be able to access all the files inside the dist directory.

f.e: <script type="text/javascript" src="./public/js/app.min.js"></script>

Comments

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.