I'm new here.
I have a website (index.html) where several css and js files are included. Locally it works fine, but if I start the node-http server (which calls the index.html), the website (localhost:8080) doesn't know the files. It shows me only basic text (i.e. <h1>) which have nothing to do with the javascript files. I checked the source code in the browser to see the index.html. But if I click on the css and js links, I'll be forwarded back to index.html.
I assume, it's a linking problem. Or do you think the problem could be in the node http server implementation? It would be very helpful for me if you could give me some support.
Thanks and best wishes, Kevin
webServer.js:
var express = require('express');
var connect = require('connect');
var http = require('http');
var path = "";
var app = connect().use(express.static(__dirname + path));
http.createServer(app).listen(8080);
index.html:
head:
<!-- Cascading Style Sheets -->
<link href="css/custom.css" media="screen" rel="stylesheet" type="text/css" >
<link href="css/rickshaw.css" media="screen" rel="stylesheet" type="text/css" >
<link href="css/envision.css" media="screen" rel="stylesheet" type="text/css" >
body:
<h1>Data monitoring</h1>
<!-- Drawing rickshaw based charts -->
<div id="chart-type1"></div>
<div id="chart-type2"></div>
<!-- Drawing envision based charts -->
<div id="chart-TimeSeries"></div>
<div id="chart-RealTime"></div>
<!-- JavaScript -->
<script type="text/javascript" src="lib/d3.min.js"></script>
<script type="text/javascript" src="lib/rickshaw.js"></script>
<script type="text/javascript" src="js/chart.js"></script>
<script type="text/javascript" src="js/chartTimeSeries.js"></script>
<script type="text/javascript" src="js/chartRealTime.js"></script>
<script type="text/javascript" src="js/collectionJson.js"></script>
You have to define routes for all your files in a way like this:
var http = require ('http');
var fs = require('fs');
var port = '8080';
var server = http.createServer(function (req, res) {
if (request.url === '/') {
fs.readFile('index.html', function(err, data){
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data, 'utf-8');
});
} else if (request.url === '/css/custom.css') {
/*Read /css/custom.css file*/
} else if (request.url === '/path/to/other.file') {
/*Read /path/to/other.file*/
}
}).listen(port);
But this is difficult to read and write so it's better to use a Web Framework for this. You can try Express or the framework written by me: Simples. You can put all your static files in a directory then use this code:
var simples = require('simples');
var server = new simples(8080);
server.serve('path/to/staticFiles');
// or in some special cases:
server.get('/some_url', function (connection) {
connection.header('X-Some-Header', 'Header Value'); // Set a header
connection.drain('some_local_file.ext');
});
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