Displaying local images in static html served by NodeJS - html

I have a NodeJS app that renders index.html, but I can't get index.html to find the images in the folder it's located in.
Here are the contents of index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get ('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(80, function(){
console.log('listening on *:80');
});
It serves index.html successfully but all images I supply it are broken links.
The following html does not work
<img src="img/myimage.png">
and my file structure is
myApp - folder
index.js
index.html
img - folder
myimage.png
I've tried several variations such as
<img src="/img/myimage.png">
<img src="./img/myimage.png">
I've also tried placing the image directly in the app folder with index.html and trying
<img src="myimage.png">
But the link to the image is still broken.

const express = require("express");
const app = express();
If you have the images in a folder named "Images" and you want to point to the image in the folder as "img/myimage.png", then use this:
app.use('/img', express.static(__dirname + '/Images'));
This way you can also keep your actual images folder name private.

I was able to resolve the issue by changing
var app = require('express')();
into
var express = require('express');
var app = express();
I then added
app.use(express.static(__dirname + '/img/'));

In the declaration of static file you will use in the express app, you have to put your files (images, songs, file) into public folder. Then, your express and ejs will show your file from the public folder as a root of that file.
var express = require("express");
var app = express();
app.use(express.static('public'));
app.set("view engine", "ejs");
app.get("/", function(req, res){
res.render("main");
});
app.listen(3000, function(req, res){
console.log("Auth server started!");
});
EJS folder is right here.
<h1>Secret Page!</h1>
<img src="anna.jpg"/>
<img src="https://i.imgur.com/NcXbX08.jpg" alt="">
After all, reload your nodejs app.

Do you mean broken links in the browser ? so the browser can not open the links rendered in index.html ?
The browser will probably need full paths to the images .. it doesn't seem that your node server is sending the full paths in the index.html file it passes to the browser.. have a look on that ..

Related

Serving HTML, CSS and JS using Node.js and Express.js

const express = require('express');
const path = require('path');
const app = express ();
app.use(express.json('public'))
app.get('/PKorn/zealtech', function(req, res) {
res.sendFile(path.join(__dirname, '/public/Ko.html'));
});
app.listen(4402);
when i using /PKorn is work with css but when i use /PKorn/zealtech work page but css is missing
Try to change app.use(express.json('public')) to app.use(express.static('public')).

Cannot GET /ejs file

I'm trying to get the stat of a survey page done with html
when I try to connect to the ejs view of the webpage it gives me Cannot GET /showResults
// Entry point for the application
// express application
var express = require('express');
// require the controller we make
var surveyController = require('./surveyController');
var app = express();
// set up template engine
app.set('view engine', 'ejs');
// static file serving
app.use(express.static('./public'));
// fire function from surveyController
surveyController(app);
// listen to port
app.listen(8080);
console.log('listening port 8080');
I have an HTML view of the webpage and app.js file that seem to run on the console but I get the error when I log into http://localhost:8080/showResults
Here you can use ejs as you view by below settings in your app.js
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// use res.render to load up an ejs view file
app.get('/', function(req, res) {
res.render('<folder>/index');
});

nodeJs display on web browser

Just want to display my node.js result on web browser..
is it possible?...
here's my code:
const testFolder = 'texts/';
const fs = require('fs');
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
})
when I try to run that code on cmd it works. The code gets all the .txt file on a specific directory.
here's the result:
then when i tried to load it on my browser the result goes like this
Im also planing to add all the result filename to database mysql once the node.js code fixed.. is that also possible?..
thank you.. this is my first time to create a node.js
Use the express router to accept GET request from your browser :
const express = require('express');
const fs = require('fs');
const app = express();
const testFolder = 'texts/';
// To set your public directory and use relative url
app.use(express.static(__dirname + 'your_public_dir'));
// When you access to localhost:8080, it will send GET '/' request
app.get('/', function(req,res) {
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
});
});
Nicolas is right, express can achieve this. Just remember to install it using NPM, this can be done by executing following command under the directory where package.json is:
npm install --save express
however, you would also need to write into response of the server so it shows on website. So for example, using Express:
app.get('/', function(req,res) {
res.write("whatever you want to display");
res.end()
});

Why does my server adds a mystery style to index.html?

I set up a basic node, express, react app and express is serving static content including my css. When I view source I noticed that index.html has this added in the head tag:
<style type="text/css">* {}</style>
It's defiantly not in the actual file. Where did this come from?
Also, I don't see my actual css rendering on the page. However I do see the css file is loading in chrome network tab. I also see bootstrap style fine and they are served the same way. What's going on here?
My server:
var express = require('express'),
bodyParser = require('body-parser'),
http = require('http'),
path = require('path');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
http.createServer(app).listen(8080), function () {
console.log('Express server listening on port 8080');
});
This is what I have in my css
body{
color: red;
}
The answer was from #godfrzero - a chrome extension was causing the mystery style.

How to acess path permission in Express nodejs?

I am completely new in express node.js . I have a folder structure like :
/Express
--server.js
--index.html
--home.html
/css/
/js/
/images
/fonts
In index.html i am accessing some javascript (js folder) , images (images folder) , fonts (fonts folder) . Also i am linking home.html from index.html page . I need to block accessing home.html directly also .
I wrote a server.js with express-ws like this :
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
var path = require('path');
//accessing index.html
app.get('/', function(req, res){
res.sendFile(path.join(__dirname+'/index.html'));
});
//How can i acess all the files inside the JS , CSS , Image and Font folder here ???
//Also How can i link home.html from Index.html File and block home.html accessing publicly
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log(msg);
});
console.log('socket', req.testing);
});
app.listen(8888);
Any suggestions how can i access all the files inside the JS , CSS , Image and Font folder from index.html with server.js ? Also linking home.html from index.html with direct access block .
You should create a separate folder for static content like public or anything else and then use express.static() to serve static content. So here would be your updated directory structure
/Express
--server.js
--index.html
--home.html
--/public/ (directory)
--/css/ (directory)
--/js/ (directory)
--/images/ (directory)
--/fonts/ (directory)
and your updated code would be
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
var path = require('path');
//for js, css, images and fonts
app.use(express.static(path.join(__dirname, 'public')));
//accessing index.html
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'index.html'));
});
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log(msg);
});
console.log('socket', req.testing);
});
app.listen(8888);
add following after requiring path
// serve index.css at localhost:3000/index.css
app.use(express.static('css')); // looks in current directory for css folder
// serve index.js at localhost:3000/static/index.js
app.use('/static', express.static('js')); // looks in current directory for js folder and appends /static to URL
app.use(express.static('fonts'));
Reference on serving static files from express