Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS Express is not defined when I try to serve static files

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?

like image 726
bernas Avatar asked Dec 06 '22 18:12

bernas


2 Answers

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});
 });
like image 145
QoP Avatar answered May 19 '23 10:05

QoP


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');
like image 25
Rajdeep Gautam Avatar answered May 19 '23 10:05

Rajdeep Gautam