Reputation: 109
I have a basic script source link:
// index.html
<script src="/js/jquery.js"></script>
Which doesn't work, despite the file existing. I tried to link to it in the Node.js server but it threw an error that express wasn't defined, yet it is.
//server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var clientlist = [];
app.get('/', function(req, res) {
res.sendfile('index.html');
app.use(express().static('/js/jquery.js'));
});
Upvotes: 2
Views: 6582
Reputation: 138
Before your file name put __dirname,'index.html'. New code will be res.sendfile(__dirname + 'index.html');
And also your first line is wrong it should be var express = require('express');
Upvotes: 0
Reputation: 134
Here is my solution.
You may want to replace '/var/www/nodeserver', with the directory, you are working in!
First of all, don't use res.sendfile()
, it is deprecated, use res.sendFile()
instead.
Or just serve a complete directory:
This could be your 'index.js' in '/var/www/nodeserver':
// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// Change 3000 to whatever port, you want to access the site with"http://127.0.0.1:3000"
var port = process.env.PORT || 3000;
server.listen(port, function() {
console.log("Server listening at port "+port);
});
// Routing
var dir = __dirname+'/public'; // Path of the index.js but one dir further (public)
app.use(express.static(dir)); // serve all files in '/var/www/nodeserver/public/'
And you would need to have a 'package.json', containing this:
{
"name": "nameofyourapplication",
"version": "versionofyourapplication",
"dependencies": {
"express": "^4.10.2",
"socket.io": "^1.3.7"
}
}
Then install the dependencies defined in the 'package.json', with this command: npm install
, while in the directory '/var/www/nodeserver/'.
This will install all the dependencies, locally, so it will create a folder named 'node_modules', in '/var/www/nodeserver'.
Next you just need to put all the files you want to serve, into the 'public' folder in '/var/www/nodeserver' and run the 'index.js' with node index.js
.
Your filetree should then look something like this:
That should do it!
Upvotes: 2
Reputation: 14688
Your requires are wrong, and hence express is not defined
Chamnge your first line var app = require('express');
var express = require('express');
var app = express();
Upvotes: 2