Node Js html css [duplicate] - html

This question already has an answer here:
Style sheet - not loading with web page
(1 answer)
Closed 5 years ago.
****Css File Cannot connect with the below****
it is in the flow of
root
/index.html
/server.js
/css/style.css
My /server.js Code
var http = require('http'),
fs = require('fs');
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(8000);
});
**CSS css/style.css**
.raj{
background-color: red;
}
**html /index.html**
<html>
<head>
<title></title>
<!-- <link rel="stylesheet" type="text/css" href="/css/style.css" /> -->
<link rel="stylesheet" type="text/css" href="/css/style.css" />
</head>
<body>
<span class="raj">
asldfasd <br/>
fasd <br/>
fas <br/>
dfa <br/>
sdf <br/>
sadf <br/>
asd <br/>
fas <br/>
df <br/>
sad <br/>
</span>
</body>
</html>
css cannot connect with this above html file

The problem is caused by your web server not checking the path of the URL request but is rather going to return the same HTML file no mater the path or file extension you use. To get around this shortcoming of the node http module I would recommend utilizing a framework such as express.js
Or if you only want to serve static files I would recommend you use http-server, you can install it using the following command:
npm install http-server -g
After installation you can navigate to the folder you store your html and CSS files in then run your webserver using the following command:
http-server
You can read more about the module here

Just Replace this line of code :
<link rel="stylesheet" type="text/css" href="/css/style.css" />
with this,
<link rel="stylesheet" type="text/css" href="./css/style.css" />

Related

How to include css file in node express?

I know this question has been asked many times but I cannot seem to see what the issue is with my code. I am trying to create a pdf by using a html file. This works but the css file I include is not getting included. I have read through all the previously asked questions and tried the solutions but my issue is still not resolved.
Here is my code.
html file:
<!DOCTYPE html>
<html>
<head>
<meta charest="utf-8" />
<title>Hello world!</title>
<link rel="stylesheet" href="/css/template.css">
</head>
<body>
<div class="document">
<div class="page" size="A4">
<h1>testing this!!</h1>
{{#each tickets}}
<div class="section">
<div>
<div class="ticketNumber" >
No. {{this.ticketNumber}}
</div>
</div>
<div>
<div class="generalStyle">{{this.prizeName}}</div>
<div class="generalStyle">
Name: {{this.customerName}}
</div>
<div class="generalStyle">
Phone: {{this.customerPhone}}
</div>
<div class="generalStyle">
Address: {{this.customerAddress}}
</div>
</div>
</div>
{{/each}}
</div>
</div>
</body>
</html>
This is where I am storing my css file
and in app.js
app.use(express.static(path.join(__dirname, 'public')));
and lastly this is where I create my pdf by sending my html file.
var document = {
html: html,
data: {
tickets: tickets,
},
path: "./output.pdf",
};
pdf.create(document, options)
.then(res => {
console.log("created!!", res)
})
.catch(error => {
console.error(error)
});
};
The file gets created but the css is not included. Any solutions?
Use it :=>
app.use('/public', express.static('public'));
Use it to link stylesheet :=>
<link rel="stylesheet" href="/public/css/template.css">
All file are served at "/public/"
Docs are at https://expressjs.com/en/starter/static-files.html
You Used the statement is used to create a static server it need a index.html
which is served as 'http://url/index.html' and 'http://url/css/template.css' which can be accessed by index.html. It use '/' route for serving files
But you are using template engine so it is best practice to specify the path at which you want to serve your static files.

Unable to access CSS File in Node JS

i am a beginner in node.js
i have 3 files
cal.js
cal.html
style.css
neither my node.js is accessing css file nor html is accessing it .
earlier when i used internal css html file was perfect but node was not .
help me in refrence to this below code
const express= require("express");
const bodyparser =require("body-parser");
const app=express();
app.use(bodyparser.urlencoded({extended:true}))
app.get("/",function(req,res){
res.sendFile( __dirname+"/cal.html");
console.log(__dirname);
});
app.post("/",function(req,res)
{
var n1=Number(req.body.num1);
var n2=Number(req.body.num2);
var n=n1+n2;
res.write('<h1 class="result">sum is='+n+'</h1>');
res.send();
})
app.listen(2000,function()
{
console.log("server is running");
});
html file
<!DOCTYPE html>
<html>
<head>
<title>server </title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form action="/" method="post">
<input type="text" name="num1" placeholder="number1">
<input type="text" name="num2" placeholder="number2">
<button type="submit" name="button">calculate</button>
</form>
<script src="cal.js"></script>
</body>
</html>
css file
body{
width: 100%;
height: 100%;font-family: cursive;
background-color: pink;
}
.result{
color: green;
background-color: yellow;
}
You need to use express.static middleware in order to serve static files.
I see in you code that the HTML file is located in __dirname, so this line should work for you:
app.use(express.static(__dirname));
try to add a dot in here
res.sendFile( __dirname+"./cal.html");
and in here
<link rel="stylesheet" type="text/css" href="./style.css">
This is the standard way of doing it:
CSS and JS file should be placed in folder in the following structure:
project_root
|
----index.js(or)app.js {node.js file}
|
----shared
|
----css
| |
| ----<CSS Files>
----js
|
----<JS Files>
in your express app file, after app.use(bodyparser.urlencoded({extended:true})), add
app.use(express.static('shared'))
Access necessary CSS and JS files from html by using /css/<filename> /js/filename
Example

How to load CSS and Bootstrap files into server using node.js?

I have a html file called myfile.html that displays 'Hello World'. My css file called myfile.css is used to insert background image. My bootstrap files are used to insert a image in the form of a circle.
The HTML file is as follows:
<!DOCTYPE html>
<html>
<head>
<title>MY FILE</title>
<link rel="stylesheet" type="text/css" href="public\css\bootstrap.css">
<link rel="stylesheet" type="text/css" href="public\myfile.css">
</head>
<body>
<h1>Hello World!!</h1>
<img src="public\pinky.jpg" class="img-circle">
</body>
</html>
My CSS file is as follows:
body {
background-image: url('fishy.jpg');
}
My node.js file called new.js is as follows:
const express = require('express')
const app = express()
app.use(express.static('public'))
app.get('/',function (req,res) {
console.log(__dirname)
res.sendFile(__dirname+"/myfile.html")
})
app.listen(3000, function() {
console.log('Example app listening on port 3000!')
})
My main folder is called Bootsstrap and it has the following contents:
Bootsstrap
-myfile.html
-public /*Folder*/
/*inside public folder*/
-myfile.css
-css
-js
-fonts
-fishy.jpg /*background image*/
-pinky.jpg /*circular image*/
I open Command Prompt from Bootsstrap folder and run
node new.js
I get the message as:
'Example app listening on port 3000!'
When I open Chrome Browser and type localhost:3000, I get only 'Hello World'.The images are not getting displayed. I get an Error 404.
What can I do in order to run my HTML file in server using node.js by including all my css and bootstrap files?
You must not use the public path in your html. Also, in URLs use always forward slashes. Backslashes are just for Windows directories.
<!DOCTYPE html> <html> <head> <title>MY FILE</title>
<link rel="stylesheet" type="text/css" href="/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="myfile.css">
</head> <body> <h1>Hello World!!</h1>
<img src="pinky.jpg" class="img-circle"> </body> </html>
replace
<link rel="stylesheet" type="text/css" href="public\css\bootstrap.css">
<link rel="stylesheet" type="text/css" href="public\myfile.css">
by
<link rel="stylesheet" type="text/css" href="css\bootstrap.css">
<link rel="stylesheet" type="text/css" href="myfile.css">
If you want to serve static files, such as html files, css, images, you need to make them available for the public. In your existing setup, only myfile.html is available for the public. Since you use css and other files from your server, you need to make them available also. The best way to achieve is to create a public folder and let express to make all the files available in the public folder.
Add to node.js
app.use('/', express.static('public'));
and rename your myfile.html to index.html
and in your index.html file
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="myfile.css">
For example, your node.js should look like something
const express = require('express');
const app = express();
app.use('/', express.static('public'));
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
For more info Serving static files in Express
Edit
Your folder structure should be. no need of bootstap folder
public //public folder
-index.html
-myfile.css
-css
-js
-fonts
-fishy.jpg
-pinky.jpg

Using express.js to render html, but html is not able to fetch JS files

I am using express.js to an HTML file which further calls a bunch of JS files. The server seems to be working, however the JS and CSS files configured within the HTML are not being fetched by the browser.
var express = require('C:/Program Files/nodejs/node_modules/express/lib/express')
var app = express()
var path = require('C:/Program Files/nodejs/node_modules/path/path')
app.use(express.static(__dirname + '/lib'));
app.use(express.static(__dirname + '/js'));
app.use(express.static(__dirname + '/css'));
app.use(express.static(__dirname + '/img'));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
My html file is:
<html>
<head>
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<script src="./css/source-sans-pro.js"></script>
<link href="css/ratchet.css" rel="stylesheet">
<link href="css/styles.css" rel="stylesheet">
</head>
<body>
<script id="home-tpl" type="text/x-handlebars-template">
<header class="bar-title"><h1 class="title">Employee Directory</h1> </header>
<div class="bar-standard bar-header-secondary"><input class='search-key' type="text" style="height:31px;"/></div>
<div class="content"><ul class='list'></ul></div>
</script>
<script id="employee-li-tpl" type="text/x-handlebars-template">
{{#.}}
<li>
<a href="#employees/{{this.id}}" class="tappable">
<img src='img/{{firstName}}_{{lastName}}.jpg'/>
<p>{{this.firstName}} {{this.lastName}}</p>
<p>{{this.title}}</p>
<span class="chevron"></span><span class="count">{{reports}} </span>
</a>
</li>
{{/.}}
</script>
<script id="employee-tpl" type="text/x-handlebars-template">
<header class="bar-title"><a class="button-prev" href="#">Back</a><h1 class="title">Details</h1></header>
<div class='content'>
<div class="details">
<img src='img/{{firstName}}_{{lastName}}.jpg'/>
<h1>{{firstName}} {{lastName}}</h1>
<h2>{{title}}</h2>
<h2>{{city}}</h2>
</div>
<ul class="list inset" style="clear:both;">
{{#if managerId}}
<li> <p>View Manager</p><p>{{managerName}}</p><div class="action-icon icon-manager"/></li>
{{/if}}
{{#if reports}}
<li> <p>View Direct Reports</p><p>{{reports}}</p><div class="action-icon icon-reports"/></li>
{{/if}}
<li><img src="/pix/byron_bay_225x169.jpg" ></li>
<li><img src="/pix/byron_bay_225x169.jpg" </li>
<li> <p>Message</p><p>{{cellPhone}}</p><div class="action-icon icon-sms"/> </li>
<li><p>Email</p> <p>{{email}}</p><div class="action-icon icon-mail"/></li>
<li><p>Map</p> <p>{{city}}</p><div class="action-icon icon-location"/></li>
</ul>
</div>
</script>
<script id="reports-tpl" type="text/x-handlebars-template">
<header class="bar-title"><a class="button-prev" href="#">Back</a><h1 class="title">Direct Reports</h1></header>
<div class='content'>
<div class="details">
<img src='img/{{firstName}}_{{lastName}}.jpg'/>
<h1>{{firstName}} {{lastName}}</h1>
<h2>{{title}}</h2>
<h2>{{city}}</h2>
</div>
<ul class="list"></ul>
</div>
</script>
<script src="./phonegap.js"></script>
<script src="./lib/fastclick.js"></script>
<script src="./lib/zepto.min.js"></script>
<script src="./lib/handlebars.js"></script>
<script src="./js/storage/memory-store.js"></script>
<script src="./js/HomeView.js"></script>
<script src="./js/EmployeeView.js"></script>
<script src="./js/ReportsView.js"></script>
<script src="./js/main.js"></script>
</body>
</html>
When I render this using an IIS server, it works perfectly fine.
you don't need to specify paths for node modules,
just do this:
const express = require('express');
const app = express();
const path = require('path');
First, I'd discourage you from using absolute paths when using node. I'd suggest configuring your Windows environment, so it works correctly with npm, then package.json should tell the npm what modules are required.
When you finish with your configuration your first line should look like this:
var express = require('express');
Additionally, consider moving on to es6 and use const/let instead of var. But that's another topic.
Your problem is that resources files are unknown for the browser.
For express, it's better to run it locally and use it in a browser navigating to localhost: PORT.
Then, resources could be requested from relative urls like "/css/foo.css".
Then, when your website is deployed it won't get lost when the hostname changes.
Make sure that you're script 'src' is correct in your html page. If your css is in you styles folder you'd have to source it like so
<link rel="stylesheet" href="/styles/style.css">
Also make sure that the order of your files are correct. You will want to source your js first. If all else fails try using the jq or js cdn. Google Jquery CDN or whatever language you're using and copy and paste the cdn in your <head>. I wouldn't recommend doing it regularly. CDN's don't work without internet.

Linking CSS to HTML background color

I am using node.js to run a local website and am having trouble linking the css to html.
The html is:
<!DOCTYPE html>
<html>
<head>
<title> Name </title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body id="background">
<h1> My Website </h1>
<span style="float:right">
Google
</span>
</body>
and css is:
#background {
background-color: #0099FF;
}
I have not been able to view the effects of the css on the website and am not able to change the background color.
I have checked online resources and it seems as if the syntax is correct. The css file style.css is in the same directory as the html. The html is working on the local website but not the css.
update: i am adding the app.js file
var http = require('http'),
fs = require('fs');
fs.readFile('./header.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(8080);
});
Your syntax looks correct. Definitely check the browser console to see if there is error with finding the css file. I would check to make sure that the css file is indeed named "style.css".
try doing class="background"
and then in css do .background instead of #background
Try putting this code at the line under your title tag
<base href="/">
This thread might help you more