how to display alert box in using html+javascript and node - javascript

I am running node project with html and javascript. How can I display the alert box in html.
My html (index.html)
<!DOCTYPE html>
<html>
<head>
<script src="./watch.js"></script>
</head>
<body onload="showBox()">
<h1>Heading</h1>
<p>Paragraph</p>
</body>
</html>
watch.js
function showBox(){
alert("this is alert box");
}
server.js
var http = require('http');
var fs = require('fs');
const PORT=8080;
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(PORT);
});
Error

I think that the problem is that you are not telling nodeJS where your statics files are.
For me, the simplest way is to set the server with Express
$ npm install express
And then setting up the server and where your static directory is:
var express = require('express');
var app = express();
//setting middleware
app.use(express.static(__dirname + 'public')); //Serves resources from public folder
var server = app.listen(5000);
There are other ways to doit using Native NodeJS, here are some resources:
Nodejs.org - How to serve static files
Also, you can write the script directly in your html file:
<!DOCTYPE html>
<html>
<head>
<script>
function showBox(){
alert("this is alert box");
}
</script>
</head>
<body onload="showBox()">
<h1>Heading</h1>
<p>Paragraph</p>
</body>
</html>

Your server is only ever returning index.html, no matter what path is requested. So, your watch.js is never loaded. The contents of index.html are returned instead of watch.js.
Either handle the other paths in your server code, or use something like Express.static, which does this for you.

Your http server is only outputting the index.html file. You need to either put all your client-side code in that file, or edit your server to load the watch.js file and make it able to send either page.
The first is simpler. Here's a basic example for the second. Most browsers will assume the mime-type by the extention.
Also, change your html for the script name from "./watch.js" to just "watch.js".
I simplified this down to be easier to understand... also const is deprecated and wont work on newer versions of node.
Specifying the mime header like you did is more compatible (Chrome and Firefox will assumebased on file extension, but for example Opera does not, or didnt used to).
var http = require('http');
var fs = require('fs');
var doc = {}
doc['/index.html'] = fs.readFileSync('index.html');
doc['/watch.js'] = fs.readFileSync('watch.js');
var server = (request, response)=>{
response.end(doc[req.url]);
}
http.createServer(server).listen(8080);

Related

MongoDB not showing console.log while inserting document from html form LOCALLY

I was trying to input Text data to a MongoDB database using just a HTML form. But when I ran it locally it doesn't work. I think this had something to do with creating a Node.js server. But I can't figure out how to run a HTML file (which is index.html here). I have only learned to run just the JavaScript code alone in the Node console. I don't know how I can run this index.html locally on NodeJS.
Also I want to do this without using ExpressJS! Everything I found online showed only on how to do this using ExpressJS. Is there a reason behind it? Can't we able to do this using just NodeJS and MongoDB? (LOCALLY on Windows)
var MongoClient = require("mongodb").MongoClient;
var url = "mongodb://localhost:27017";
function addData(){
var record = document.getElementById("title").value;
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("notetest");
var record2value = { title: record };
dbo.collection("page1").insertOne(record2value, function (err, res) {
if (err) throw err;
console.log("1 document added!");
db.close();
})
})
};
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="scripts/script.js"></script>
</head>
<body>
<form onsubmit="addData()">
<input type="text" name="title" id="title">
<input type="submit" name="submit" id="submit">
</form>
</body>
</html>
UPDATE: Also I tried calling this index.html using Node. By using the following code.
var http = require('http');
var fs = require('fs');
const PORT=8080;
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(PORT);
});
But I don't know why I am not seeing the console.log from MongoDB, which should say "1 document added!".
Everywhere is using ExpressJS for this issue because we need a web server which can listen to the calls from network (Local or internet) and make it understandable in server side. You ran a http server on your own, but you need to handle request which are coming from clientside web. Due to your purpose, we need express too. Express also uses http library for creating a web server so you don't need to get worried about all that stuff. I don't know your problem with express but i suggest using express and its recommended approaches for solving this issue.
Update
This topic will help you for creating a web server just with Node.js:
Node.js server that accepts POST requests
Create a file called server.js and use above answer to create http server and then run it from a terminal with node app.js command. (Make sure that your terminal is in right directory)
Put your database related code in that section which accepts request under POST method.
Then create a javascript file for your HTML page and link it as you know with <script src="">... and simply use fetch API for sending request that http server that you just ran. Read about fetch here.

How to enqueue CSS and JS to a page on the fly with NodeJS app file

I need to get HTML page, enqueue CSS and JS files to it "on the fly" and then display it in the browser with NodeJS app file. I mean without changing HTML code of the page before getting it by NodeJS. Both CSS and JS files are in the same folder as NodeJS app file.
I'm trying this way
var fs = require('fs');
var http = require('http');
http.createServer(function (req, res) {
if(req.url === '/favicon.ico') {
res.writeHead(404);
res.end();
return;
}
var indexPageHTML = fs.readFileSync('index.html');
var indexPageHTML = indexPageHTML.toString();
var indexPageHTML = indexPageHTML.split('</head>')[0]+'<link rel="stylesheet" type="text/css" href="style.css"></head>'+indexPageHTML.split('</head>')[1];
var indexPageHTML = indexPageHTML.split('</body>')[0]+'<script src="my_client_script.js"></script></body></html>';
res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
res.end(indexPageHTML);
}).listen(80, 'localhost');
my minified index.html
<!doctype html><html><head><meta charset="utf-8"><title>Homepage title</title>
<style>html,body{height:100%;}</style></head><body>
<header></header>
<main role="main"></main>
<footer></footer>
</body></html>
In the browser I get the code I need, but none of files are loaded (CSS are not applied and JS doesn't work on the page) and in the browser console I get the error
Uncaught SyntaxError: Unexpected token <
and the warning
Resource interpreted as Stylesheet but transferred with MIME type
text/html: "http://localhost/app_style.css".
How to resolve the problem?
ps. I'm working with NodeJS in local computer on disk C inside of C:/User/Username
Ok, I've found the answer by the link NodeJS can't load css file
Just added the code
...
if(mimeType == 'text/html') {
var contents = contents.toString();
var contents = contents.split('</head>')[0]+'<link rel="stylesheet" type="text/css" href="style.css"></head>'+contents.split('</head>')[1];
var contents = contents.split('</body>')[0]+'<script src="my_client_script.js"></script></body></html>';
}
res.end(contents);
...
to the getFile() function

execute javascript from html - node.js

I hava an html file that execute js file inside.
Now I want to run this with Node.js server.
I can see that it write the html file in it (it write 'hi (:') but ignored the js file.
this is the 'server.js' file:
var fs = require('fs');
var http = require('http');
var content;
//read the file
fs.readFile('index.html', function read(err, html) {
if (err)
{
throw err;
}
content = html;
http.createServer(function(request,response)
{
response.writeHead(200,{"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8081);
console.log("listening on port 8081");
});
and this is the 'index.html' file:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="script.js"> </script>
<script> </script>
</head>
<body>
<div id="empty">
hi :)
</div>
</body>
</html>
Thanks for your help! (:
You've created a server that responds to every single request with the contents of index.html--so when the <script> tag asks the server for the script.js file, the server incorrectly sends it index.html again.
In your createServer handler, you'll want to look at the incoming request and figure out which file the request is asking for, and send different data back accordingly.
To handle this situation more robustly, where you don't have to have an if statement for every file you might want to send, you can use an abstraction over your createServer handler to detect and send static files automatically. This question contains several solutions that may help put you on the right track.

Where to put the image file in node.js?

I have the following directory structure in Linux with just 3 files in it:
/home/nikhil/test_img/
server.js
page.html
pic.jpg
This is a simple node.js hello world setup without using express or any other library
Code for server.js
var http = require("http"), fs = require('fs');
var path = require('path');
var root = path.dirname(require.main.filename);
var filePath = path.join(root + '/page.html');
var port = 8889;
function onRequest(request, response) {
fs.readFile(filePath, function (err, html) {
if (err) {
throw err;
}
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(html);
response.end();
});
}
http.createServer(onRequest).listen(port, function () {
console.log("Server has started at port " + port);
});
This simply creates the server which displays page.html on any request to localhost:8889
Code for page.html
<html>
<head><title>Page</title></head>
<body>
<h1> Hello World </h1>
<img src="pic.jpg" alt="image">
</body>
</html>
This is a simple webpage with Hello World heading and an image.
Now, the error is that the image does not get displayed when the page is loaded when I hit localhost:8889 on my browser. But, the image is displayed when I simply open the webpage through my browser (not via node).
I have also tried changing the src to
"/home/nikhil/test_img/page.html"
"file:///home/nikhil/test_img/page.html"
"localhost:8889/page.html"
But, none of these work
Also, I tried printing my location in javascript using <script>alert(document.location.pathname);</script>
The path printed was
/
Whereas, when I ran the page directly in my browser (without node), it was
/home/nikhil/test_img/page.html
Where do I need to put the image file for this to work?
Your code says that each request should serve the file that corresponds to filePath i.e. the html file page.html. This is fine for the page request itself, but the img tag in your html page creates a separate request for the image pic.jpg which should exist in the same path as the page. But instead of serving the img file, which means your request handler would return something with header Content-type: image/jpg, your request handler again responds with the html page's contents and header Content-Type:text/html.
You need to differentiate what to serve, based on what is being requested.

Node.js simplest code not working

As I am a newbie to Node.js and is learning from different articles. So, far I have learnt, my code is
At server side with app.js
var http = require('http');
var app = http.createServer(function(req,res)
{
req.on('end',function()
{
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello');
});
});
var io = require('socket.io').listen(app);
io.sockets.on('connection',function(socket)
{
socket.emit('connect',{msg:'Hello Client'});
socket.on('client_Says',console.log);
});
app.listen(3000);
At client side with index.html
<script type="text/javascript" src="//localhost:3000/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('//localhost:3000');
socket.on('connect',function(data)
{
alert('Server says '+data.msg);
socket.emit('client_Says',{data:'Hello Server'});
});
</script>
What is that I am doing wrong in above code? When I run app.js in console, it says info - socket.io started but when I run http://localhost:3000 it just keep requesting server.
plus I want to know that is it true that wherever on my pc I create my folder for Node and place app.js and index.html files like above in it and run http://localhost:3000 in browser will automatically make that folder my site folder for localhost after running app.js in Node console?
In your app.js update code to this
var http = require('http'),
fs = require('fs'), //<--- File Module
index = fs.readFileSync(__dirname + '/index.html');
var app = http.createServer(function(req,res)
{
res.writeHead(200, {'Content-Type': 'text/html'}); //<-Updated to text/html
res.end(index); //<---I am sending page
});
Hope that solves your problem
You're not supposed to do this on server side:
socket.emit('connect',{msg:'Hello Client'});
because connect is a default event which is emitted on a successful connection from the server. So when a client connects, the server fires its default 'connect' event, but here you're also triggering your event named connect which might be causing problem.

Categories

Resources