Images not displaying on node.js presented webpage - javascript

I have a node.js server with the following code:
var http = require('http'),
fs = require('fs'),
index = fs.readFileSync(__dirname + '/index.html');
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});
app.listen(80);
When I use an tag in index.html, no images will show:
<html>
<body>
<img src="settings.gif" />
</body>
</html>
The image is in the same directory as the server.js file and index.html
Edit: Images will show if I use a full URL to another site. Example:
<img src="http://yellowicons.com/wp-content/uploads/Gear-Icon-2.png" />

Perhaps you may decide to separately create a public/images directory beneath and copy the settings.gif as well as any other images into the image directory that can be publicly viewable.
Next you will need to make known to node where the static reference for the public directory is by adding these 2 lines into node.js
var publicDir = require('path').join(__dirname,'/public');
app.use(express.static(publicDir));
After which, the image could be tagged in the html as
<html>
<body>
<img src="images/settings.gif" />
</body>
</html>

Try using absolute path. In case of failure, keep the image file in public/images directory. and use this address:
<img src="http://localhost:3000/images/Heading.png" />

I guess your server doesn't know where your images are, I don't see where your code specifies that. I suggest you use nodejs with express to handle all your routes, just google it and have tons of examples.
Good luck

Before access image fine html static page we have to add static folder location in the nodejs middleware using app.use() method
staticPages
| - image.png
| - index.html
code:
server.js
app.use(express.static(path.join(__dirname, "staticPages")));
index.html
before server start: <img src="./image.png" />
after server start: <img src="http://localhost:3000/image.png" />

Related

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>

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

How to hide image link, i.e mask the repository from where it is fetched

I need to develop functionality in which there are multiple images fetched from different resources. Users(Clients) should not see repository details from which images are fetched.
If not possible, is there a way to create a directory at the client (browser cache) and put those images there and delete them after user logouts.
The only way to do this would be to have a backend generating data: URLs on the server instead of referencing images by URL. Any URL you send to the client can be discovered through developer tools or network sniffers.
I don't know what server you are using at background.
I've created a example using node sever.
My Server:
const express = require('express')
, app = express()
, http = require('http').createServer(app);
app.use(express.static('./views'));
app.get('/image1', (req, res) => {
res.sendFile('public/test.png', { root: __dirname });
});
http.listen('8080', () => {
console.log('Server started');
});
My HTML:
<html>
<head>
</head>
<body>
<img src='./image1' />
</body>
</html>

Image not found in webpage served with node.js and express

I'm trying to serve a very simple html page with one image. I'm using node.js and express. The html loads, but the image does not. Instead i am given the error GET https://localhost:3000/stockMarketPhoto.jpg 404 (Not Found) The image is in the same directory as everything else is. Somewhere I saw suggested that app.use(express.static('public')); is supposed to help with this, but no dice. I've tried both <img src="stockMarketPhoto.jpg"> and <img src="https://localhost:3000/stockMarketPhoto.jpg">. How can I get the image in my HTML page to load?
Here's the html in question
<body>
<img src="stockMarketPhoto.jpg">
</body>
Here's the javascript.
const https = require('https');
const express = require("express")
const fs = require('fs');
let app = express();
app.use(express.static('public'));
app.listen(3000, () => {
console.log("listening on 3000");
});
app.get('/', (req, res) => {
console.log('connected');
res.sendFile(__dirname + '/index.html')
})
First i recommend you read this from the express docs.
Serving Static files in express
and in here:
<img src="stockMarketPhoto.jpg">
you are missing a '/' should look like this:
<img src="/stockMarketPhoto.jpg">
Your image should be inside the public folder in your app. What i do is usually put an Image, Javascript, and css folder inside my public folder and import them like this:
src='/Image/example.jpg'
src='/Javascript/example.js'
src='/css/master.css'
Basically when you tell express to serve your static files in the public folder, express then interprets the above example like this.
'public/Image/example.jpg'

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