Loading Basic HTML in Node.Js

Loading basic HTML in Node.js

I just found one way using the fs library. I'm not certain if it's the cleanest though.

var http = require('http'),
fs = require('fs');


fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);
});

The basic concept is just raw file reading and dumping the contents. Still open to cleaner options, though!

Loading basic HTML in Node.js inside string html

To send a formatted string with express.js, you can do:

app.get("/html", async (req, res) => {
const msg = await getMsgFromDB(); // An example of how you fetch data from DB
res.send(`<!DOCTYPE html>${msg}</html>`);
});

Render basic HTML view?

You can have jade include a plain HTML page:

in views/index.jade

include plain.html

in views/plain.html

<!DOCTYPE html>
...

and app.js can still just render jade:

res.render(index)

Load in html page with Node

As an alternative, you could also use the Express static middleware and create a route method for answering GET requests to your page root by serving the file. Also, to avoid platform-specific issues with file paths, you can use path.join(), where __dirname sets the absolute path to your working directory.

const http = require('http');
const path = require('path');
const express = require('express');
const app = express();

app.use(express.static(path.join(__dirname, '')));

app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});

http.createServer(app).listen(8080, function(){
console.log('HTTP server listening on port 8080');
});

javascript not loading in HTML file - nodejs + http

Your logic for appending child nodes seems okay.

I think you should try changing your src="start.js" to src="./start.js" or src="/start.js" just to make sure that you're referencing the path properly. Add a console.log() statement in your start.js to make sure that it is being loaded.

EDIT: Make sure you are hosting your file on your server. You could add something like express or connect to help.

To use connect, run npm install --save connect in your project directory.

var connect = require('connect'),
directory = '/path/to/Folder'; // probably just '/' for all your files

connect()
.use(connect.static(directory))
.listen(80);

console.log('Listening on port 80.');

Refer to their docs for full instructions and more examples using http.

Trying to load my html file using nodejs to create login page

you can solve it in two ways, first you can install view engine like ejs and use res.render (if you want more about it i can explain)

Second you can response with the HTML file like this: (works only with express and you have express)

app.get('/yourRotue', function(req, res, next){
res.sendFile(__dirname + '/yourPath/htmlFile.html');
});

How to use EJS (basic):
First please install EJS with npm install ejs install body parser npm install body-parser
now you need to create two folders on the root folder, public and views.
inside views you can create a folder auth and put your EJS files there.
then on your app.js (or index.js, the main file) add view engine middleware:

(*notice that you dont need to require ejs, also notice you dont need to install path its built in with node)

//import body parser on top (to parse json/urlencoded/text..
const bodyParser = require('body-parser');
//import path so you can use it for the public folder
const path = require('path');

//this line makes public folder public so you can store js/css/image...
app.use(express.static(path.join(__dirname, 'public')));

//use the body parser as middleware
app.use(bodyParser.json({ limit: '200mb' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.text({ limit: '200mb' }));

//this line tells node js to use ejs
app.set('view engine', 'ejs');
//this line make sure that the views folder is the folder with the ejs files
app.set('views', 'views');

//now your route will look like this:
app.get(/routeName, (req,res,next) => {
let example
//you return response with render, to render the file you want.
// you dont write the views folder name, only the file name without .ejs
// elso you can run functions here and later send the response to the front end
function(){
example = 1 + 1 * 5
}
// *very often the function above is to find something in the db
return res.render('auth/ejsFileName', {
pageTitle: 'some page title for the example',
exampleKey: example
})
})

I can suggest you to use mvc (models, views, controllers) structor, if you want to know more about it you can open new question or to search about it.

EJS:

put your css and js in public folder, you can create js folder and css folder inside the public folder and then put the css in js in their folder.

*notice you dont need to write ./public in the route.

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/someCssFile.css">
<!-- here is the title that comes from the back end -->
<title><%= pageTitle %></title>
</head>
<main>
<h1>Here you can see the example with the function<%= exampleKey %></h1>
</main>

<script src="/js/someJsFile.js"></script>
</body>

</html>

the file look like html but it has .ejs
there is many things you can do with ejs like to loop through values.. i would suggest to learn a bit more.
this is the basic it should work.

For the post request i need to know if you are posting a form as urlEncoded or json. so i can show you how it should look like.

display html page with node.js

but it ONLY shows the index.html file and NOTHING attached to it, so no images,
no effects or anything that the html file should display.

That's because in your program that's the only thing that you return to the browser regardless of what the request looks like.

You can take a look at a more complete example that will return the correct files for the most common web pages (HTML, JPG, CSS, JS) in here https://gist.github.com/hectorcorrea/2573391

Also, take a look at this blog post that I wrote on how to get started with node. I think it might clarify a few things for you: http://hectorcorrea.com/blog/introduction-to-node-js



Related Topics



Leave a reply



Submit