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

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

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.

get() method or function

Unresolved function or method get().
I'm new in js and node and I got stuck with this while trying to make a chat using sockets. Here is the code:
.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
server.listen(8888);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.on('send message', function (data) {
io.sockets.emit('new message', data);
});
});
.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>glupi chat</title>
<style>
#chat{
height: 500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message">
<input type="submit">
</form>
<script src='jquery-3.2.1.js'></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$document.ready(function () {
var socket = io.connect();
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.submit(function (e) {
e.preventDefault();
socket.emit('send message', $messageBox.val());
$messageBox.val('');
});
socket.on('new message', function (data) {
$chat.append(data + "<br/>");
});
});
</script>
</body>
</html>
I'm using IntelliJ IDEA, I have every module and library that I need installed.
It appears that you have no route for the jQuery file you specify with this:
<script src='jquery-3.2.1.js'></script>
A nodejs express server does not server ANY files by default so unless you have a general purpose route for your static files or a specific file for that jQuery file, your express server will not know how to serve that file when the browser requests it.
You have several possible choices for how to fix that:
Change the jQuery URL in the script tag in your web page to point to one of the public CDNs for jQuery. There are often performance advantages to doing this. For example, you could change to this: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>.
Use express.static() on your server to configure a directory of static assets that will be automatically served by express when requested by the browser.
Create a specific route for the jQuery file just like you did with your exist app.get('/', ...)that responds to the/` GET request.

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}`);
});

Why can't I load images in phaser.io

I keep getting the same errors
GET http://localhost:3000/star.png 404 (Not Found)
Phaser.Loader - image[star]: error loading asset from URL ./star.png
Phaser.Cache.getImage: Key "star" not found in Cache.
But I am not loading the asset incorrectly. Here is my code:
var express = require('express');
var app = express();
var fs = require('fs');
app.get('/', function(req, res) {
var index = fs.readFileSync('./index.html', "utf8");
res.send(index);
});
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Phaser</title>=
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.4.4/phaser.js"></script>
<script type="text/javascript">
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', {
preload: preload,
create: create,
update: update
});
function preload() {
game.load.image('star', './star.png');
};
function create() {
game.add.sprite(0, 0, 'star');
};
function update() {};
</script>
</body>
</html>
Here is my PATH for this game:
/home/me/dev/games/phaser
I have all my files (three files, app.js, index.html, and star.png) in the same directory (phaser). Why the heck does it not grab the .png file??? Am I not linking to it correctly? It's sitting right there, why does the GET request not grab it? Why does phaser.loader throw an error? I have tried a hundred different things but it just won't load. It's getting really frustrating.
You are only hosting 1 route (/) - you need to serve the assets with a static server. See http://expressjs.com/starter/static-files.html
Using game.load.image() just adds to the loader queue.
You need to execute game.load.start() to actually kick the loading sequence off.

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