Reputation: 113
I am using Node.js as my server and I am having some trouble serving up my JS and CSS files. For some reason, index.html
can't seem to find them. When I load up my browser, I get this error:
My file system structure:
public
css
main.css
normalize.css
js
main.js
upload.js
plugins.js
views
index.html
server.js
HTML
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="manifest" href="../public/site.webmanifest">
<link rel="apple-touch-icon" href="../public/icon.png">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="../public/css/normalize.css">
<link rel="stylesheet" href="../public/css/main.css">
<script src="../public/js/vendor/modernizr-3.5.0.min.js"></script>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js">
</script>
<script src="../public/js/plugins.js"></script>
<script src="../public/js/main.js"></script>
<script src="../public/js/upload.js"></script>
</head>
server.js
var express = require("express");
var app = express();
var path = require("path");
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'views/index.html'));
});
My guess is I am serving up the public folder incorrectly in server.js
. I get Cannot GET /public when I try to access that folder directly on browser. Any experts can help me here?
Upvotes: 1
Views: 1963
Reputation: 586
The way you are loading the static assets is wrong. Express looks up the files relative to the static directory, so the name of the static directory should not be part of the URL.
If you use app.use(express.static(path.join(__dirname, 'public')));
, then you can load static assets at http://host:port/css/* or http://host:port/js/* .
If you use app.use('/public', express.static(path.join(__dirname, 'public')));
, then you can load static assets from public directory at /public path. For example, http://host:port/public/css/*
Upvotes: 2