Serving HTML file from Node server - html

Pretty much purely for pedagogical purposes, I'm serving both my front and back end data out of my one node server. Right now, I'm at the point where I've received my client request successfully, created some data based on said request, am able to console log it, etc. Everything is fine up to that point. My issue is that in the event that my data is only an html file, which is being read with the fs library, it will not render on the page when I attempt to serve it out in my res.end() or res.write(). I can see it's exactly what I want and expect when I console log it, but it just doesn't render in the browser. Any help would be appreciated. I've got it set up to where I'm handling my requests in an "if/else" wherein I only have the two scenarios of "/" (home), in which case I serve the html file, and anything else because the server really only needs to handle those two events. Thanks in advance.
Edit. This is what I have so far:
function responseHandler(req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
if (req.url.match("fav")) {
res.end("");
return;
}
else if (req.url.match("/endpoint")) {
var input = req.url.match(/endpoint\/(.*)/)[1];
var output = endpoint.toHTML(decodeURI(input));
res.end(data);
console.log(input, req.url)
}
else {
fs.readFile("index.html", "utf8", function(err, data) {
console.log("data:" + data);
var input = req.url.match(/endpoint\/(.*)/)[1];
var output = endpoint.toHTML(decodeURI(input));
});
}
res.end();
}
I can see the data in the console which, in the last case, is just my HTML file. It just won't render in the page.

How did you attempted to serve the html with res.end() and res.write() ?
I just made a small test here, and this works:
app.js
var http = require('http');
var fs = require('fs');
var html = fs.readFileSync('hello-world.html');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
}).listen(8000);
hello-world.html
<h3>Hello World</h3>
Edit: To match with your code, try this:
function responseHandler(req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
if (req.url.match("fav")) {
res.end("");
return;
} else if (req.url.match("/endpoint")) {
var input = req.url.match(/endpoint\/(.*)/)[1];
var output = endpoint.toHTML(decodeURI(input));
console.log(input, req.url);
// we have no data variable in this scope
res.end("");
// I added a return statement in each step
// Just to be clear that we don't want to go if any
// condition have fit, since we cannot call res.end()
// more than once
return;
} else {
fs.readFile("index.html", "utf8", function(err, data) {
// error handling
if (err) return res.end(err);
// now we have the data
console.log("data:" + data);
res.end(data);
});
return;
}
}

Serving html in asynchronous way works something like that;
var fs = require('fs');
var http = require('http');
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('index.html', function(err, data){
if(err){
return console.log(err);
}
res.end(data);
});
}).listen(8080);
console.log('Server is running on Port: 8080');

Related

Why does Node.js on http-server freeze when you enter url parameter

I'm setting up a node.js server, and want to fix problem with freezing loading using http-server lib.
I've tried doing other URL parameter methods but it doesn't work and doesn't show any errors on console.
var url = require('url');
http.createServer(function (req, res) {
var queryData = url.parse(req.url, true).query;
if (req.url == '/watch') {
if (!queryData.id) { res.write("Missing watch id?"); res.end(); }
res.end();
fs.readFile('player.html', function (err, html) {
if (err) {
throw err;
}
res.writeHeader(200, {"Content-Type": "text/html"});
res.write(html + "<div id='b6'>" + queryData.id + "</div>");
res.end();
});
}
});
I expect the output to get URL parameter and show the player.html.
There may be more than one issue, but as-written, you have an errant res.end(), before you read in your player.html and return it to the response. Remove that line and see if it behaves as you expect.

In Node.js Html and Static files css, js. The result is "Waiting for localhost" loading

var http = require('http'),
fs = require('fs');
http.createServer(function (req, res) {
if(req.url.indexOf('.html') != -1){ //req.url has the pathname, check if it conatins '.html'
fs.readFile(__dirname + '/public/index.html', function (err, data) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}
if(req.url.indexOf('.js') != -1){ //req.url has the pathname, check if it conatins '.js'
fs.readFile(__dirname + '/public/js/material.js', function (err, data) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.write(data);
res.end();
});
}
if(req.url.indexOf('.css') != -1){ //req.url has the pathname, check if it conatins '.css'
fs.readFile(__dirname + '/public/css/material.css', function (err, data) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data);
res.end();
});
}
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
There isn't enough information here to say what is failing, but here are some options that should help you to troubleshoot.
Check the network tab to see what file/s are failing to load.
Add some console.log statements to see which code is actually running. This will narrow down what is failing.
I'd like to point out that your routing logic is pretty strange. You are only checking the extension of a file and serving the same file for every request of that type. For example, if I request /literally/any/path/to/some.js, it will always respond with material.js. I'm guessing you will want to load more js files in the future.
I recommend using a framework like express. It will let you easily serve a static file directory.
app.use(express.static('public'))
This will allow you to load any file in public as a static file.
/js/material.js -> serves public/js/material.js
/css/material.css -> serves public/css/material.css

Node.js rendering either html or css, not both

Beginning my first node.js project and I'm finding that my code renders either the html with no styling, or the css code as plain text to the screen. I open the page and see the html code, change nothing but hit refresh, and I see the css, and it switches back and forth every time I hit refresh. Can anyone tell me how to get it to apply the styling? Thanks. My code:
http.createServer(function (req, res) {
if(req.method.toLowerCase() == 'get'){
fs.readFile('path\\to\\index.html', function (err, data) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
//res.end();
});
}
if(req.method.toLowerCase() == 'get'){
fs.readFile('path\\to\\mystyle.css', function (err, data1) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data1);
//res.end();
});
}
}).listen(4000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:4000/');
The reason I have the 'res.end()'s commented out is that when I left either or both of them in, I got a 'write after end' error. But I presume my problem is somewhere in that?
Edit: Just to add, I get the same problem if I remove both IF statements. If I enclose both readFiles within the same IF statement, I get the 'write after end'.
This is what worked in the end:
var http = require('http');
var fs = require('fs');
var formidable = require("formidable");
var util = require('util');
var url = require('url');
var html;
fs.readFile(__dirname+'\\index.html', function(err, data) {
if (err){
console.log(err);
response.writeHead(404, {'Content-Type': 'text/html'});
}
html = data;
});
var css;
fs.readFile(__dirname+'\\mystyle.css', function(err, data) {
if (err){
console.log(err);
response.writeHead(404, {'Content-Type': 'text/html'});
}
css = data;
});
var js;
fs.readFile(__dirname+'\\management.js', function(err, data) {
if (err){
console.log(err);
response.writeHead(404, {'Content-Type': 'text/html'});
}
js = data;
});
var server = http.createServer(function (request, response) {
switch (request.url) {
case "/mystyle.css" :
response.writeHead(200, {"Content-Type": "text/css"});
response.write(css);
break;
case "/management.js" :
response.writeHead(200, {"Content-Type": "text/javascript"});
response.write(js);
break;
default :
response.writeHead(200, {"Content-Type": "text/html"});
response.write(html);
};
response.end();
})
server.listen(4000);
console.log('server is listening at 4000');
You could easily put all the code inside the createServer function but the key is the switch.

NodeJS: saving JSON to MongoDB

I am trying to get JSON from an API and store it into a MongoDB database.
Obviously, it doesn't work. My app seems to hang around the point where I try to save the data to the database. Please advise what to do.
Here's my code:
var express = require('express');
var router = express.Router();
var http = require('http');
var mongo = require('mongoskin');
var db = mongo.db("mongodb://localhost:27017/zak", {native_parser : true});
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
var site = 'http://www.vsechnyzakazky.cz/api/v1/zakazka/?format=json&limit=2';
function getData(cb) {
http.get(site, function(res) {
// explicitly treat incoming data as utf8 (avoids issues with multi-byte chars)
res.setEncoding('utf8');
// incrementally capture the incoming response body
var body = '';
res.on('data', function(d) {
body += d;
});
// do whatever we want with the response once it's done
res.on('end', function() {
try {
var parsed = JSON.parse(body);
} catch (err) {
console.error('Unable to parse response as JSON', err);
return cb(err);
}
// pass the relevant data back to the callback
cb(
parsed.objects
);
});
}).on('error', function(err) {
// handle errors with the request itself
console.error('Error with the request:', err.message);
cb(err);
});
}
function writeData (data, allGood){
// couple of visual checks if all looking good before writing to db
console.log('writing');
console.log(typeof data);
console.log(data);
db.collection('zakazky').save(data, function(error, record){
if (error) throw error;
console.log("data saved");
});
}
function allGood(){console.log('all done');}
getData(writeData);
// ---------------------
module.exports = router;
You are calling the save() instead of insert(). Change this part and it will work:
// this should call insert, not save
db.collection('zakazky').insert(data, function(error, record){
if (error) throw error;
console.log("data saved");
});

Get JSON data from multiple files in a unique response

There are several files containing JSON data on my server. I want to receive the data contained in those files with a single GET request.
Right now my code looks like this:
app.get('/json', function(req, res){
fs.readFile(__dirname + '/file01.json', function(err, content){
var data01 = content;
});
fs.readFile(__dirname + '/file02.json', function(err, content){
var data02 = content;
});
res.send({file01: data01, file02: data02});
});
I know this is absolutely not the way to do it, the files are still being read when the response is sent, and i'm not sure if data01 and data02 are globally defined.
But then, what is the way to do it?
Should I use a stream? Should I use multiple res.write() instead? Enlighten me.
Perfect fit for async.parallel.
var async = require('async');
app.get('/json', function(req, res) {
var work = {
file01: async.apply(fs.readFile, __dirname + '/file01.json'),
file02: async.apply(fs.readFile, __dirname + '/file02.json')
};
async.parallel(work, function (error, results) {
if (error) {
res.status(500).send(error);
return;
}
//might need string->Object here
results['file01'] = JSON.parse(results['file01']);
results['file02'] = JSON.parse(results['file02']);
res.send(results);
});
});
Use the callback of each readFile to do the next operation:
fs.readFile(__dirname + '/file01.json', function(err, content){
var data01 = content;
//Might be smart to do some err checking here
//if (err) send error
//else read the next file
fs.readFile(__dirname + '/file02.json', function(err, content){
//if (err) again
var data02 = content;
res.send({file01: data01, file02: data02});
});
});