NodeJS writing response - javascript

First of all: I am a beginner at nodeJS!
My Problem is that i have an html-file, which is complex, and i want to write an individual response in it. For example
index.js
var express = require('express');
var app = express();
var server = app.listen(3000, function () {
console.log('Listening at port 3000');
});
app.use(express.static('public'));
app.get('/', function(req, res){
res.sendFile(__dirname + 'index.html');
//
// what to write here when i want to modify the index.html before sending?
//
});
index.html
<!DOCTYPE HTML>
<html>
<div id="writehere">
<!--I would like to modify the page here-->
</div>
</html>
I hope you can help me and understood my question!

Related

Splitting HTML file doesn't work

I'm trying to build very simple web page (one page , spited into 2 parts, each part will have it's own html file):
Welcome.html & Welcome.css:
<html>
<head>
<link rel="stylesheet" type="text/css" href="Welcome.css">
</head>
<body id="bodyTag">
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
});
</script>
<div id="top" w3-include-html="/Top.html">
</div>
<div id="bottom">
bottom
</div>
</body>
</html>
#bottom {
height: 50%;
background-color: blue;
}
#top {
height: 50%;
background-color: orange;
}
I want that Welcome.html file will get the top content from external html file
Top.html
<html>
<head>
</head>
<body>
Test -> TOP
</body>
</html>
But is seems that there is no request for Top.html file in the Node.js Log:
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
app.use(bodyParser.json())
/*
* Home page
*/
app.get('/', function (req, res) {
clearLogScreen();
console.log("[/] Got request for '/'");
res.sendFile( __dirname + '/Welcome.html');
})
app.get('/Welcome.css', function(req, res) {
console.log("[/Welcome] Got request for 'Welcome.css'");
res.sendFile(__dirname + "/" + "Welcome.css");
});
app.get('/Top', function(req, res) {
console.log("[/Top] Got request for 'Welcome.top'");
res.sendFile(__dirname + "/" + "Top.html");
});
/*
* Startup
*/
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
// start
console.log("-----------------------------")
console.log("Dirname: " + __dirname);
console.log("App listening at http://%s:%s", host, port)
})
I guess I'm missing something very easy, but can't find the mistake.
Kindly checkout templatesjs; It will help insert html inside another html.
I'm not sure what "w3-include-html" is, but if it does what it is supposed to do (based on the name), then try changing its value from "/Top.html" to "/Top". Or, alternatively, try changing the url route "/Top" to "/Top.html" in your express app.
One side note: Your included html ("Top.html") should not be a complete html. Try removing html, header and body tags. It should be a fragment.

auto reload browser when file content changed, saved in nodejs

I have been working on node.js project. my requirement is I want to load.txt file on browser. when I change and save this file, content should be updated. Browser should be auto refresh.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
index.js
app.get('/', function(req, res){
res.sendFile(__dirname + '/demo.txt');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
var io = require('socket.io')(80);
var fs = require('fs');
fs.watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
// file changed push this info to client.
io.emit('fileChanged', 'yea file has been changed.');
});
index.html
<script>
var socket = io();
socket.on('fileChanged', function(msg){
alert(msg);
});
First of all you can do this with two action:
1. Watch file change on server-side. And push info to client
You can watch file with node.js.
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendFile(__dirname + '/cluster.json');
});
const io = require('socket.io')(http);
io.on('connection',function (client) {
console.log("Socket connection is ON!");
});
http.listen(80, function(){
console.log('listening on *:80');
});
var fs = require('fs');
fs.watchFile('cluster.json', function(curr, prev){
// file changed push this info to client.
console.log("file Changed");
io.emit('fileChanged', 'yea file has been changed.');
});
2. Catch "file changed" info and refresh page on client side
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="text/javascript" src="node_modules/socket.io-client/dist/socket.io.js"></script>
<script>
var socket = io("http://localhost:80");
socket.on('fileChanged', function(msg){
alert(msg);
});
</script>
</body>
</html>
The best way to do this is using WebSockets. A very good package to work with WebSockets is Socket.io, and you can use something like chokidar or the native function fs.watch to watch the file changes and then emit an messsage.
Or if you trying to do this only for development purposes, you should check webpack, gulp or other task runner that have built-in functions to do this.
Do polling for the file using Ajax. Your server could respond with {changes: '{timestamp-of-file-modify}'}. Now check if your last seen change time differs from response time.
If there is changes: window.location.reload

ReferenceError: Can't find variable: clicked in node.js

js application. Need help to resolve this issue.
I have app.js which is node, calls index.html. The index.html intern calls main.js function clicked. It works fine when I have funtion 'clicked()' embeded inside index.html using script tag. But does not work if function clicked is in a seperate js file. I think this is something regarding to node.js but unable to figure out. Please find my code below.
app.js
var http = require('http');
var fs = require('fs');
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
var request = require('request');
request('http://localhost:8000/test', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
var server = http.createServer(function(req,res){
console.log('Request was made:' + req.url);
res.writeHead(200,{'content-Type': 'text/html'});
var myReadStream = fs.createReadStream(__dirname + '/index.html','utf8');
myReadStream.pipe(res);
});
server.listen(3000,'127.0.0.1');
console.log('Listening on port 3000');
index.html
<!DOCTYPE html>
<html>
<head>
<title> Login</title>
<script type="text/javascript" src="main.js"></script>
<center>
<h1> Login </h1>
</center>
</head>
<body>
<center>
<input type="text" id="username" placeholder="UserName"></br>
<input type="password" id="password" placeholder="PassWord"></br>
<input type="button" value="Login" onclick="clicked()">
</center>
</body>
</html>
main.js
function clicked() {
var user = document.getElementById('username');
var pass = document.getElementById('password');
var checkuser = "test";
var checkpass = "123"
if (user.value == checkuser) {
if (pass.value == checkpass) {
window.alert("You are logged in as "+ "'"+user.value+"'");
open("http://www.yahoo.com");
}
else
window.alert("Incorrect username or Password");
}
else
window.alert("Incorrect username or Password");
}
ScreenShot of the Error:
This is because the Node.js server does not serve main.js correctly -- According to the browser's "Resources" panel, main.js is available, but its path is not /main.js.
Low level Node.js server code and Express framework code co-exist, which is not a good idea.
To solve the problem with low level Node.js code:
var server = http.createServer(function(req,res){
console.log('Request was made:' + req.url);
if (req.url === '/main.js') {
res.writeHead(200,{'content-Type': 'application/javascript'});
var jsReadStream = fs.createReadStream(__dirname + '/main.js','utf8');
jsReadStream.pipe(res);
return;
}
res.writeHead(200,{'content-Type': 'text/html'});
var myReadStream = fs.createReadStream(__dirname + '/index.html','utf8');
myReadStream.pipe(res);
});
To solve the problem with Express framework:
var http = require('http');
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/main.js', function(req, res) {
res.sendFile(path.join(__dirname + '/main.js')); // where main.js located.
});
app.set('port', 3000);
var server = http.createServer(app);
server.listen(port);
You are using both http and express, which is probably unnecessary. I would serve static files with app.use(express.static('public')), per the docs. Then you can serve the index with
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'))
});
And start the server with app.listen(3000);

Read css/js files with nodejs and express

I'm a real noob when it comes to nodejs, jsut started this a couple of days ago. I can't figure out why my js and css files aren't applied. There are no 404 errors so that doesn't seem to be it. I'm trying to read the files using express. I'm getting these console errors in dev tools:
GamblerScript.js:1 Uncaught SyntaxError: Unexpected token <
jquery-2.2.0.min.js:1 Uncaught SyntaxError: Unexpected token <
localhost/:5 Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:8080/css/Stylesheet.css".
(index):9 Uncaught ReferenceError: Run is not defined
Is there any one who can see what i'm doing wrong?
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sendfile('/index.html');
});
app.use(express.static(__dirname + '/public'));
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(8080);
});
<html lang="en">
<head>
<title>Dices</title>
<link rel="stylesheet" href="/css/Stylesheet.css">
<script src="/js/GamblerScript.js"></script>
<script src="/js/jquery-2.2.0.min.js"></script>
</head>
<body onload="Run();">
<div id="spinboxcontainer">
<div class="spinbox">
<span class="spinspan">Dices</span>
</div>
<div id="container">
<div id="spinner1" class="spinner">
<div id="D1.1" class="one">1</div>
<div id="D1.2" class="two">2</div>
<div id="D1.3" class="three">3</div>
<div id="D1.4" class="four">4</div>
<div id="D1.5" class="five">5</div>
<div id="D1.6" class="six">6</div>
</div>
</div>
<div id=container2>
<div id="spinner2" class="spinner">
<div id="D2.1" class="one">6</div>
<div id="D2.2" class="two">5</div>
<div id="D2.3" class="three">4</div>
<div id="D2.4" class="four">3</div>
<div id="D2.5" class="five">2</div>
<div id="D2.6" class="six">1</div>
</div>
</div>
</div>
</body>
</html>
function Run(){
alert('Welcome');
var clickNumber = 1;
document.getElementById('spinner1').addEventListener("click", function(){
alert('Your click is number ' + clickNumber + '!');
document.body.className -= ' WhiteBackground';
clickNumber = clickNumber + 1;
});
document.getElementById('spinner2').addEventListener("click", function(){
alert('Your click is number ' + clickNumber + '!');
document.body.className += ' WhiteBackground';
clickNumber = clickNumber + 1;
});
};
You messing up different approaches. If you use express there is no need to http.createServer and manually read your static files with fs.readFile. For simple static server just simplify your main file like this
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080, function() {console.log('server listening on port 8080...')})
The error you've got is because whenever the browser asks server for script files like jquery and GamblerScript your custom http server sends your index.html file back and browser tryes execute it like javascript.
There are a few things you are doing wrong.
In the bottom half of your code, in the callback passed to fs.readFile(), you create a Node server to handle all requests. The emphasized words are key here: you are creating a server using only Node's built-in features, which you shouldn't need to do when using Express; and the server handles all requests, not just those to your index.html file, as I think you intended. So, when the requests for your CSS and JavaScript come in, you are sending index.html as a response. This won't do.
Luckily, the solution is simpler than the original problem. Just do this:
'use strict';
const path = require('path');
const express = require('express');
const app = express();
// This just lets you set an alternate port with an environment variable,
// if you want.
const PORT = process.env.PORT || 8080;
// Set your static folder before any request handlers.
app.use(express.static(path.resolve(__dirname, 'public')));
// Handles request to root only.
app.get('/', (req, res) => {
// If you needed to modify the status code and content type, you would do so
// using the Express API, like so. However, this isn't necessary here; Express
// handles this automatically.
res.status(200);
res.type('text/html');
// Use sendFile(absPath) rather than sendfile(path), which is deprecated.
res.sendFile(path.resolve(__dirname, 'index.html'));
});
// Call the listen() method on your app rather than using Node's http module.
app.listen(PORT, (err) => {
if (err) throw err;
else console.log(`Listening on port ${PORT}`);
});

Express get/post method error

I'm trying to learn node.js and I'm using express to have a form that should appear here: http://localhost:4000.
I started using "hello world" which worked well. Now with this second step I have a problem. If I select post method, it appears that I cannot GET on my browser. Also, if I select post method, the following appears:
Username: undefined.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="test.js"></script>
<title></title>
</head>
<body>
<form method="get" action="/">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
Javascript
( post method is with comment)
var express = require('express');
var app = express();
/*
app.post('/', function(req, res) {
res.send('Username: ' + req.body.username);
});
*/
app.get('/', function(req, res) {
res.send('Username: ' + req.query['username']);
});
var server = app.listen(4000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
I know that most probably the error is due to something simple; I'm trying to solve alone but until now I have found no solution.

Categories

Resources