NodeJS and Express : CSS not loading - html

I have created my own server and router files to serve my html pages. The page renders, but my problem is, it renders without css styling.
I'm using express.static to serve my /public files, which in theory should serve the css file - or so I thought. I have done a Google search of my problem and looked at the links on the first couple of pages but I still cannot fix my problem. Can anyone sport my mistake?
My directory is:
NODEJS
node_modules
public
css
style.css
js
router
main.js
views
my html files
My server code is:
var express = require('express');
var app = express();
var fs = require('fs');
var url = require('url');
var path = require('path');
var http = require('http');
var router = express.Router();
var bodyParser = require('body-parser');
app.use(bodyParser());
app.use(express.static(__dirname + "/public", {maxAge: 3456700000}));
require('./router/main')(app);
app.engine('html', require('ejs').renderFile);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
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);
});
My Router code is:
var url = require('url');
module.exports = function (app) {
app.get('/', function (req, res) {
res.render('../views/default.html');
console.log("Home page displayed");
});
// Some more get requests for different pages
};
My html code is:
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>Index</title>
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/css/style.css">
</head>
[error fixed: code needed re-arranging and chrome browser needed updating to most recent version]

the css path looks wrong it should be /css/style.css instead of portalstyle.css, like this
<link rel="stylesheet" type="text/css" href="/css/style.css">

Related

Read static files with express got "Cannot Get /"

I tried to learn how to read static files with express from a reliable website. And then I found that not know why, my terminal tell me I'm success but website show me "Cannot Get /"(as following image show). I had found a lot of solution (e.g. in my html file, I add script src to socket.io) but still fail. Where can I start to deal with it? Please help me...
terminal show success
website show error
And the following is my code:
C:\...\1-on-1-webrtc\server.js
const express = require('express')
const app = express()
const http = require('http').createServer(app)
// static data
app.use('/', express.static(__dirname + '/public/'))
// TODO: Signaling
//start server listen 8080 port
http.listen(8080, () => {
console.log(`Server running in 8080`)
})
C:\...\1-on-1-webrtc\pubilc\index.html
(origin)
"hello"
(after)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>111</title>
<script src="https://cdn.socket.io/socket.io-3.0.5.js"></script>
</head>
<body>
<h1>"hello"</h1>
<script>
var socket = io();
</script>
</body>
</html>
I change Your code a little and here is my solution:
Firstly change your name of public folder to correct. Not "pubilc" only "public".
Folder & File Structure:
server.js :
const express = require("express");
const app = express();
const port = 8080;
// const http = require("http").createServer(app);
// static data
app.use("/", express.static(__dirname + "/public"));
//start server listen 8080 port
app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});
index.html (without any changes) :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>111</title>
<script src="https://cdn.socket.io/socket.io-3.0.5.js"></script>
</head>
<body>
<h1>"hello"</h1>
<script>
var socket = io();
</script>
</body>
</html>
Output :
Tested with: express 4.17.2 node 16.13.0 Linux Ubuntu 20.04 and Win10

How to Fetch multiple images in nodeJS?

So, problem is i have two jpg images you can see in HTML code. But only download.jpg is showing not lenovo.jpg but both are showing in the req.url
console image is attached and output is also attached.
HTML output
Console ScreenShot
this is my js file
//creating web server
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function(req,res){
if(req.url === "/"){
fs.readFile('./public/index.html',"UTF-8", function(err,html){
res.writeHead(200,{'content-type': 'text/html'});
res.end(html);
});
}
else if(req.url.match("\.css$")){
var cssPath = path.join(__dirname, '/public', req.url);
var fileStream = fs.createReadStream(cssPath, "UTF-8");
res.writeHead(200, {'content-type': 'text/css'});
fileStream.pipe(res);
}
else if(req.url.match("\.jpg$")){
var imagePath = path.join(__dirname,'/public',req.url);
var fileStream = fs.createReadStream(imagePath);
res.writeHead(200,{'content-type': 'image/jpg'});
fileStream.pipe(res);
}
console.log(req.url);
}).listen(3000);
My Html
<!DOCTYPE html>
<html>
<head>
<!-- <meta charset="utf-8"> -->
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My HTML Page</title>
<link rel="stylesheet" type="text/css" href="./css/base.css">
</head>
<body>
<h1> My First Heading From the Page of html </h1>
<img src="./images/download.jpg">
<img src="./images/lenovo.jpg">
</body>
</html>
Look at size of your lenovo.jpg image it have very high resolution please use low resolution or define width and height in img tag.
If you don't have a strict requirement not to use express, I suggest you to use express, and you can handle it with express' static file handling method:
https://expressjs.com/en/starter/static-files.html

simple express json parser

trying to copy a simple example but still cannot parse json post request,
ideas?
looking in the borwser (firefox) network tab, I see the request with json params.
but the server log comes out empty.
client
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var man = {
name:'name',
fam:'familiy'
};
var xhttp = new XMLHttpRequest();
var url = "http://localhost:8080/";
xhttp.open("post", url, true);
xhttp.send(JSON.stringify(man));
</script>
<title>Json Test</title>
</head>
<body>
Json Test
</body>
</html>
server
//require the express nodejs module
var express = require('express'),
//set an instance of exress
app = express(),
//require the body-parser nodejs module
bodyParser = require('body-parser'),
//require the path nodejs module
path = require("path");
//support parsing of application/json type post data
app.use(bodyParser.json());
app.post('/', function(req, res){
res.setHeader('Content-Type', 'application/json');
console.log(req.body);
res.send("done");
});
//Start listen on port
const port = 8080;
app.listen(port);
console.log("Node js listen on port " + port + "...");
You are not setting Content-Type header with your AJAX request. Please change to the following.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var man = {
name:'name',
fam:'familiy'
};
var xhttp = new XMLHttpRequest();
var url = "http://localhost:8080/";
xhttp.open("post", url, true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(JSON.stringify(man));
</script>
<title>Json Test</title>
</head>
<body>
Json Test
</body>
</html>
well....
I guess I forgot these as well (working now)
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, **POST**, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});

Displaying local images in static html served by NodeJS

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 ..

I receive a GET error when trying to serve html page with image using Node.js

I am new to Node.js and am unable to find a way to solve my issue. I have written a server using Node.js to serve a html webpage. The problem is that it wont display the images that are in the same folder. I am trying to serve my webpage as well as my images and css file. Any help would be appreciated.
Relevant code:
server:
var http = require('http');
var fs = require('fs');
const PORT = 8080;
function handleRequest(request, response) {
console.log(request.url);
var bool = 0;
var index = fs.readFileSync("index.html", {
encoding: "utf-8"
});
if(request.url == "/")
{
bool = 1;
response.end(index);
}
else if(request.url == "/index" || request.url == "/index.html")
{
bool = 1;
response.end(index);
}
else if(bool == 0)
{
response.statusCode = 404;
response.end("Not Found");
}
}
var server = http.createServer(handleRequest);
server.listen(PORT, function() {
console.log("Started server on http://localhost:%s", PORT)
});
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Personal Webpage</title>
<link rel="stylesheet" href="index-css.css"/>
</head>
<body>
<h1>Welcome!</h1>
<p>My paragraph.</p>
<img src="/family.jpg" alt="Family" style="width:342px;height:513px;">
<img src="/Another.jpeg" alt="Another" style="width:500px;height:500px;">
</body>
</html>
I recommend use app.use(express.static(__dirname + '/FOLDER_NAME')) in order to expose a folder to serve static files to the client. Here is the documents about serving static files using express.
Edit: Here is a simple working example of serving a index.html using express
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});