Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js sending html file doesn't load linked files (css, js)

Tags:

node.js

extjs

I am trying to make az ExtJS application with a Node.js server. My server code currently looks like this:

var express = require('express');

var app = express();

app.get('/', function (req, res) {
    res.sendfile(filedir + '/index.html');
});

app.get('/employees', function(req, res){
console.log("hello");
});

app.listen(3000);

When I open localhost:3000 in a browser, the html file is load, but not correctly. Checking in firebug I see that itt cannot find the linked files in html. For example

"NetworkError: 404 Not Found - http://localhost:3000/ext-4/ext-debug.js".

This is quite logical, since the file doesn't exist on that URL. My question would be how to fix this issue, so it could find every single linked file on my filesystem.

I'm clearly doing something wrong or missing something, I am totally new in node.

like image 512
Zuller Avatar asked Feb 17 '23 20:02

Zuller


2 Answers

Doesn't look like you're configuring Express' static file handler.

Try adding this code:

app.configure(function() {
    app.use(express.static(path.join(__dirname, 'public')));
    app.use(express.bodyParser());
    app.use(express.logger("short"));
});

It would go right after var app = ... like this:

var express = require('express');

var app = express();
app.configure(function() {
    app.use(express.static(path.join(__dirname, 'public')));
    app.use(express.bodyParser());
    app.use(express.logger("short"));
});

app.get('/', function (req, res) {
    res.sendfile(filedir + '/index.html');
});

app.get('/employees', function(req, res){
    console.log("hello");
});

app.listen(3000);

And then place your static files under the ./public directory.

like image 81
Daniel Avatar answered Feb 23 '23 04:02

Daniel


You'll want to use some static middleware such as: http://www.senchalabs.org/connect/static.html

note express inherits connect so you can

app.use(express.static(filedir));

Or the full thing:

var express = require('express');

var app = express();

app.use(express.static(filedir));

app.get('/employees', function(req, res){
  console.log("hello");
  res.send("hello");
});

app.listen(3000);
like image 22
generalhenry Avatar answered Feb 23 '23 04:02

generalhenry