How to add a Javascript file to HTML while running on nodejs - javascript

I create simple nodeJs server this is my server.js file:
var http = require('http');
var fs = require('fs');
var path = require('path');
var server = http.createServer(function(req, resp){
// Print the name of the file for which request is made.
console.log("Request for demo file received.");
fs.readFile("www/index.html",function(error, data){
var filePath = '.' + req.url;
var extname = path.extname(filePath);
var contentType = 'text/html';
if(extname == '.js'){
contentType = 'text/javascript';
console.log("extname is .js")
}
resp.writeHead(200, { 'Content-Type': contentType });
resp.end(data, 'utf-8');
});
});
server.listen(8081, '127.0.0.1');
this is my HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Professor Test DApp</title>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet' type='text/css'>
</head>
<body class="container">
<h1>A Simple Test Professor DApp</h1>
<div class="table-responsive">
</div>
Apply
</body>
<script src="https://cdn.rawgit.com/ethereum/web3.js/develop/dist/web3.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script type="text/javascript" src="index112.js"></script>
</html>
and this is my js file:
function apply(){
console.log("apply in js file called")
}
when I open it in the browser without a server it works fine but when I run it in server the js file cannot be detected.

I think you need to serve static files. create public folder and move index112.js in public folder. use the express.static built-in middleware function as per the following.
app.use(express.static(path.join(__dirname, 'public')));

Please check your index112.js file path because while running on server there might be possiblity that server is not able to find the file try giving absolute or relative path of the file in src attribute this might help.
Absolute or Relative Path Info

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.

html file cannot find uploads directory

I have an html file that is supposed to display every picture in the uploads directory, however it does not recognize an uploads directory. I am using a nodejs server. Here is my html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>gummy bear</title>
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link href="css/styles.css" rel="stylesheet">
</head>
<body>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script>
var dir = "/uploads/";
var fileextension = ".jpg";
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='" + dir + filename + "'>");
});
}
});
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
and here is what my directory layout looks like:
app.js css index.html javascripts LICENSE node_modules package.json README.md upload.html uploads
and inside of uploads is:
➜ uploads ls
1.jpg
Thanks in advance!
Looking through the sample code it seems like the HTML file expects some HTML to be returned from http://localhost:3000/uploads.
The questions is why does the /uploads endpoint not return anything but instead returns a 404 response?
The answer to this would lie in the main executable Javascript file in the node.js application. Likely a file called server.js or index.js.
Here is an example of how you would go about creating the correct node.js application for you HTML file to work:
server.js
app.all('/uploads', function (req, res) {
var folder = './public/uploads',
html = '<html><body>##files##</body></html>';
fs.readdir(folder, (err, files) => {
var fileHrefs = '';
files.forEach(function (file) {
fileHrefs += '' + file + '';
});
html = html.replace('##files##', fileHrefs);
res.send(err || html);
})
});
This snippet of code iterates over all files in the uploads directory and wraps them in an a tag which is then returned by the server.
index.html
To make your index HTML file work a couple small changes need to be made:
change $(data).find() to $(data).filter()
remove the directory from the image source. change <img src='" + dir + filename + "'> to <img src='" + filename + "'>
Complete working sample
You can also find the whole working sample here: https://github.com/kohlikohl/list-images-in-dir

CSS file is not working in NODE js

For some reason, I have attached my css file to my html file. And then i open the html file using express in node js. However, the css file does not open when i run the webserver through node js. I thought since the css file is included in html that it should run??
html
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
</head>
<body>
<h1>Reading in Value</h1>
<form action="/" method="post" >
<br/>
<label>Enter a UDP command in hex</label>
<br/><br/>
<input type="number" name="number" id="number">
<br/><br/>
<input type="submit" value="Submit" name="submit">
<meta name="viewport" content="width=device-width, initial-scale=1">
</form>
</body>
</html>
node js
//Sending UDP message to TFTP server
//dgram modeule to create UDP socket
var express= require('express')
var fs= require('fs')
var util = require('util')
var dgram= require('dgram')
var client= dgram.createSocket('udp4')
var bodyParser = require('body-parser')
var app = express()
var app2= express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//Reading in the html gile
app.get('/', function(req, res){
var html = fs.readFileSync('index2.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
//Sends user command utp
app.post('/', function(req, res){
//Define the host and port values
var HOST= '192.168.0.172';
var PORT= 69;
//buffer with hex commands
var message = new Buffer(req.body.number, 'hex');
//Sends packets to TFTP
client.send(message, 0, message.length, PORT, HOST, function (err, bytes) {
if (err) {
throw err;
}
res.send('UDP message sent to ' + HOST +':'+ PORT);
});
});
//CREATES ANOTHER PORT
app2.get('/', function(req, res){
client.on('message', function (message) {
res.send('received a message: ' + message);
});
});
app.listen(3000, "192.168.0.136");
app2.listen(8000, "192.168.0.136");
console.log('Listening at 192.168.0.172:3000 and Recieve message will be on 192.168.0.172:8000')
<link rel="stylesheet" type="text/css" href="style.css" media="screen" /> tells the browser to ask (with GET) the server for the CSS at /style.css.
Look at your server code. You've told it what to do with GET / (app.get('/', function(req, res){ etc), and you've told it what to do for POST /, but you haven't told it what to do for GET /style.css.
The Express manual covers this.
Wherever you're serving your files from, you need to set in the express config like this:
app.use(express.static('public'));
This would work if you're static files were being stored in a folder called public. Please see this link for more documentation: http://expressjs.com/en/starter/static-files.html

Webcam doesn't display when node.js it's running

I have a script that takes a picture from my webcam.
it's working fine when i runs locally or when i see in a online server.
But when i run the html file from the node.js, it doesnt show the view from my webcam.
how to fix that?
MY SERVER IN NODE:
// app.js
var http = require('http');
var fs = require('fs');
sys = require('util');
var server = http.createServer(function(request, response){
fs.readFile(__dirname + '/index.html', function(err, html){
console.log("oi");
response.writeHeader(200, {'Content-Type': 'text/html'});
response.write(html);
response.end();
});
});
server.listen(3000, function(){
console.log('Executando Servidor HTTP');
});
MY HTML:
<!DOCTYPE html>
<html>
<head>
<title>Javascript Webcam Demo - <MyCodingTricks/></title>
</head>
<body>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- A button for taking snaps -->
<form>
<input type=button class="btn btn-success" value="Take Snapshot" onClick="take_snapshot()">
</form>
<div id="results" class="well">Your captured image will appear here...</div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="2/webcam.min.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="'+data_uri+'"/>';
Webcam.upload( data_uri, 'upload.php', function(code, text) {
// Upload complete!
// 'code' will be the HTTP response code from the server, e.g. 200
// 'text' will be the raw response content
});
} );
}
</script>
</body>
</html>
Your program seems to be sending the content of index.html for every request (for html, icons, scripts, etc.). Maybe try using express to serve static files properly:
var express = require('express');
var app = express();
app.use('/', express.static(__dirname));
app.listen(3000, function(){
console.log('Executando Servidor HTTP');
});
It's even easier than the way you want to write it, because to make your script work you would have to manually route the requests based on the request object to properly send scripts and different assets, make sure to handle MIME types, paths like ../.. etc.
Also you may want to move your static files (html, css, js) to a different directory like static and change the app.js like this:
var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/static'));
app.listen(3000, function(){
console.log('Executando Servidor HTTP');
});
so that no one will be able to get your app.js code by browsing to: http://localhost:3000/app.js

Simple node.js server that sends html+css as response

I've created basic http server that sends html file as response. How can I send css file as well so client using browser will see a html using css ?
The code I have:
var http = require('http');
var fs = require('fs');
var htmlFile;
fs.readFile('./AppClient.html', function(err, data) {
if (err){
throw err;
}
htmlFile = data;
});
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.end(htmlFile);
});
//Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
What I have tried(it seems it does not work - client sees only css file content here):
var http = require('http');
var fs = require('fs');
var htmlFile;
var cssFile;
fs.readFile('./AppClient.html', function(err, data) {
if (err){
throw err;
}
htmlFile = data;
});
fs.readFile('./AppClientStyle.css', function(err, data) {
if (err){
throw err;
}
cssFile = data;
});
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/css"});
response.write(cssFile);
response.end();
response.writeHead(200, {"Content-Type": "text/html"});
response.write(htmlFile);
response.end();
});
//Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="AppClientStyle.css">
</head>
<body>
<div class=middleScreen>
<p id="p1">Random text</p>
</div>
</body>
</html>
css file :
#CHARSET "UTF-8";
.middleScreen{
text-align:center;
margin-top:10%;
}
I don't want to use express here(it is just for learning purpose)
What you have written in your first snippet is a web server that responds with the body of your HTML file regardless of what URI the browser requests.
That's all nice and well, but then with the second snippet, you're trying to send a second document to a closed response handle. To understand why this doesn't work, you have to understand how HTTP works. HTTP is (for the most part) a request->response type protocol. That is, the browser asks for something and the server sends that thing, or an error message of some sort, back to the browser. (I'll skip over keep-alive and methods that allow the server to push content to the browser--those are all far beyond the simple learning purpose you seem to have in mind here.) Suffice it to say that it is inappropriate to send a second response to the browser when it hasn't asked for it.
So how do you get the browser to ask for a second document? Well, that's easy enough... in your HTML file you probably have a <link rel="stylesheet" href="AppClientStyle.css"> tag. This will cause the browser to make a request to your server asking it for AppClientStyle.css. You can handle this by adding a switch or if to your createServer code to perform a different action based on the URL the browser requests.
var server = http.createServer(function (request, response) {
switch (request.url) {
case "/AppClientStyle.css" :
response.writeHead(200, {"Content-Type": "text/css"});
response.write(cssFile);
break;
default :
response.writeHead(200, {"Content-Type": "text/html"});
response.write(htmlFile);
});
response.end();
}
So, first, when you access your server at http://localhost:8000 you will be sent your html file. Then the contents of that file will trigger the browser to ask for http://localhost:8000/AppClientStyle.css
Note that you can make your server far more flexible by serving any file that exists in your project directory:
var server = http.createServer(function (request, response) {
fs.readFile('./' + request.url, function(err, data) {
if (!err) {
var dotoffset = request.url.lastIndexOf('.');
var mimetype = dotoffset == -1
? 'text/plain'
: {
'.html' : 'text/html',
'.ico' : 'image/x-icon',
'.jpg' : 'image/jpeg',
'.png' : 'image/png',
'.gif' : 'image/gif',
'.css' : 'text/css',
'.js' : 'text/javascript'
}[ request.url.substr(dotoffset) ];
response.setHeader('Content-type' , mimetype);
response.end(data);
console.log( request.url, mimetype );
} else {
console.log ('file not found: ' + request.url);
response.writeHead(404, "Not Found");
response.end();
}
});
})
Start this in the same directory as your HTML and CSS files. The above is simplistic, error-prone and INSECURE. But it should be sufficient for your own learning or local development purposes.
Keep in mind that all the above is far less succinct than just using Express. In fact, I'm not sure why you wouldn't want to use Express, so I'm going to try to convince you to try it:
$ npm install express
$ mkdir www
$ mv AppClientStyle.css www/
$ mv AppClient.html www/index.html
Your script will look like: (Borrowed from Express Hello World)
var express = require('express')
var app = express()
app.use(express.static('www'));
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log('Express app listening at http://%s:%s', host, port)
})
Then run your script and point your browser to http://localhost:8000. It really is that painless.
Integrate the CSS right into your AppClient.html file. There are different ways to do so:
External CSS file
Create a styles.css file (or any other file name) in the same directory as your html file. Then add
<link rel="stylesheet" type="text/css" href="styles.css">
to your <head> section of your HTML document.
OR
Right in your HTML file
Add a
<style>
YOUR STYLES RIGHT HERE
</style>
to your <head> section of your HTML document.

Categories

Resources