I am trying to serve static content for the app from the "www" directory in the application directory.
my folders look like this:
-www
--node_modules
--js
--index.js
--index.html
--package.json
I want to use the main.js file that is inside the js folder but when I try to use the
<script src="/js/main.js"></script>
in the index.html, my console give me a GET error and 404 file not found.
My code looks something like this:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static(__dirname + '/www'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
when I try to run the server I get the error:
app.use(express.static(__dirname + '/www');
ReferenceError: express is not defined
Can someone give me a hint of why this is happening?
You forgot to import express.
You also should move your non static files outside "www" since that's the path you want for the "static files".
var express = require('express');
var path = require('path');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var publicPath = path.resolve(__dirname, 'www');
app.use(express.static(publicPath));
app.get('/', function(req, res){
res.sendFile('index.html', {root: publicPath});
});
In your code, you haven't declared any variable named as express. Without variable named as express how you can call it's variables/functions/keys.
To use express./anything/ you have to declare express variable in your code. that can be done via
var express = require('express');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With