execute javascript from html - node.js - javascript

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.

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.

Nodejs local website, working from 127.0.0.1, but doesnt load css/js when other device access it [duplicate]

This question already has an answer here:
Link index.html client.js and server.js
(1 answer)
Closed 2 years ago.
I have a simple web app that I am using to control a device, its just html+css+js.
I want to host that app on a raspberry pi and use it as a local server, so that I can open that app from tablets, pcs, phones etc, whatever I want.
I tried setting up a nodejs server to host the app, this is the code that I used, found it somewhere here on the forum:
var http = require('http');
var fileSystem = require('fs');
var server = http.createServer(function(req, resp){
fileSystem.readFile('./index.html', function(error, fileContent){
if(error){
resp.writeHead(500, {'Content-Type': 'text/plain'});
resp.end('Error');
}
else{
resp.writeHead(200, {'Content-Type': 'text/html'});
resp.write(fileContent);
resp.end();
}
});
});
server.listen(8081);
console.log('listening');
And it is kinda working. If I open the app from http://127.0.0.1:8081 on the computer on which it is hosted (mind you atm I am not on the raspberry, still testing on my personal pc) it is working as expected, if I directly open the index.html it is also working just fine.
But if I go and try to open it from my phone, or from my laptop from http://192.168.0.2:8081 it is not working. By not working I mean the following:
On the laptop it just renders the bare html and nothing else, there are several errors in the console about 'unexpected token <' I have one for each of my javascript files, and it is pointing at the first row of my HTML file the row
On my phone, same issue, I connected it for USB debugging to chrome to see the Console, I have the same errors screenshot: http://prntscr.com/s65x0t
Here is my HTML code, I did some research, many people were pointing out that some of the JS files that I have linked in my HTML may have incorrect directory or file name, but at least I dont see an issue there:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
<script type="text/javascript" src="./js/jquery-3.5.0.js"></script>
<script type="text/javascript" src="./assets/scripts/main.js"></script>
<script type="text/javascript" src="./js/easy-numpad.js"></script>
<script type="text/javascript" src="./js/jquery-modal.js"></script>
<script type="text/javascript" src="./js/Model.js"></script>
<script type="text/javascript" src="./js/UI.js"></script>
<script type="text/javascript" src="./js/config.js"></script>
<link href="./css/main.css" rel="stylesheet" type="text/css" >
<link href="./css/easy-numpad.css" rel="stylesheet" type="text/css" >
Did You Serve Assets of HTML in Node Js?
You Can Server Static Content in Node js With the following code:
fs.readFile(__dirname + req.url, function (err, data) {
if (err) {
resp.writeHead(404);
resp.end(JSON.stringify(err));
return;
}
resp.writeHead(200);
resp.end(data);
});
Replace this and use http://192.168.x.x/index.html to open your html file and html file call for assets.
maybe require to remove . from address of assets files
(for example
<script type="text/javascript" src="./js/jquery-3.5.0.js"></script> convert to <script type="text/javascript" src="/js/jquery-3.5.0.js"></script>)
All requests to your server will return the index-html page which is why you see the Syntax Error/Mime-Type warning when Chrome tries to load the js/css files.
The solution is to set up additional routes/handling for other html, javascript and css files.
However, I recommend using express and just serving the content statically, as express takes care of this automatically:
// server.js
const express = require('express');
const app = express();
const port = 8081;
app.use(express.static('public'));
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`));
With that just create a directory called public in the same directory as the server.js and all static content will be served automatically from there, e.g.
- your-server-app
-- server.js
-- public
--- index.html
--- js
---- test.js
and an example for the index.html page:
<html>
<script src="js/test.js"></script>
<body>
<h2>Hello from Index page</h2>
</body>
</html>

Can't load local resources with Node.js server

I'm developing a simple server that loads an HTML page after a request.
The code works fine, but i'm not able to load the local resources "connected" to my HTML page (CSS and Javascript files), i get the error mentioned in the title.
This is my Node.js server:
var server = http.createServer(function(request, response){
var path = url.parse(request.url).pathname;
console.log("Print path:"+ path);
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
response.end();
break;
case '/index.html':
console.log("print full address:"+__dirname + path);
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 404");
response.end();
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, "utf8");
response.end();
}
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
response.end();
break;
}
});
server.listen(5000);
The index.html file is loaded, but i won't be able to access to all the local scripts and stylesheets inside my HTML file.
This is my HTML (short version, just the script and stylesheet part):
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>A Pen by Mattia Surricchio</title>
<link rel='stylesheet' href='02cbe09766a509e291eb2a444.css'>
<link rel='stylesheet' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src='02cbe09766a509e291eb2a444.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/tone/13.8.9/Tone.min.js'></script>
<script src="script.js"></script>
</body>
All the files are in the same folder of my node.js file, so the server, HTML, CSS and Javascript files are all in the same folder.
I'm accessing the server with http://localhost:5000/index.html in my browser.
I checked the paths with console.log() and they seem correct (the HTML is loaded properly, the problem are the CSS and Javascript files inside the page).
What could be the problem?
PS: If i load the index.html page by itself (just opening it with the browser), all the files are loaded and showed correctly.
EDIT:
I partially solved the problem moving to express.js, here's my new server (i followes this answer:nodejs/express include local js file):
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var path = require('path');
var express = require('express');
app.use(express.static(path.join(__dirname, 'Pad')));
app.get('/', function(req, res) {
res.redirect('index.html');
});
My directory structure is the following:
root/
app.js //this is my node.js server
node-modules
package.json
Pad/
index.html
script.js
style.css
With this solution i'm able to load the HTML file, including the script.js file and the style.css that are linked inside the HTML file.
However, i'm also using local modules (in this particular case i'm using Tone.js and Tonal.js) which have been installed using npm inside the folder node-modules.
How do i access those resources? I'm getting error 404.
Do i have to move those resources inside my Pad folder?
You need to define a route for your CSS file(s) as you do it for index.html
case '/style.css':
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(fs.readFileSync(__dirname + path, 'utf8'));
res.end();
break;
You need to call those files seperately like you call html file in the first place. Create direct url list for files that you want to parse first, then make get requests for them seperately.

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

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

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.

Categories

Resources