HTML not Linking to CSS Properly - html

Html not properly loading css file.
Here is my html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<h1>TEST</h1>
</body>
</html>
and my style.css file is in the same folder as my .html file shown above.
Here is my style.css file:
body {
background: red;
}
When I inspect the "Network" tab of the Chrome developer tools, my style.css file is listed as "pending".
Any idea how to fix this? I have tried disabling AdBlock and clearing the cache.
My server is being run on node.js, not sure if that's relevant here...
Here is my server.js:
var http = require("http");
// server sends all requests to router file
var router = require("./router.js");
// set the port #
port = "8080";
// server to listen for requests
http.createServer(function (request, response) {
router.home(request, response);
}).listen(port);
// Console will print the message
console.log('Server running at http://127.0.0.1:' + port + '/');
and here is my router.js file:
var renderer = require("./renderer.js");
var url = require("url");
var htmlHeader = {'Content-Type': 'text/html'};
function home(request, response) {
if (request.url === "/") {
if (request.method.toLowerCase() === "get") {
response.writeHead(200, htmlHeader);
renderer.view("header", {}, response);
renderer.view("footer", {}, response);
response.end();
}
}
}
module.exports.home = home;
and finally the renderer.js file:
// to read contents of [view].html files
var fs = require('fs');
// insert contents into [view].html file
function mergeValues(values, content) {
// cycle over keys
for (var key in values) {
// replace all {{key}} with the value from the values object
content = content.replace("{{" + key + "}}", values[key]);
}
// return merged content
return content;
}
// handle the view passed as an argument
function view(templateName, values, response) {
// find the [view].html file in the /views/ folder
var fileContents = fs.readFileSync('./views/' + templateName + '.html', {encoding: "utf8"});
// insert values in to the content of the view file
fileContents = mergeValues(values, fileContents);
// write out contents to response
response.write(fileContents);
}
module.exports.view = view;
Thanks

As static files are requested just like any other HTTP request, the server will not locate your css file because you have no route for it.
You will need to add something like:
if (request.url === "/style.css") {
fs.readFile('style.css', function (err, data) {
response.writeHead(200, {'Content-Type': 'text/css', 'Content-Length': data.length});
response.write(data);
response.end();
});
}
There are of course better ways to serve static files with module that locates existing files automatically for you. This is ment as a simple answer only.

Have you privileges to access to the css file? Try:
chmod 777 style.css

Related

How to Host HTML on a different server than Heroku

I have my index.html and the necessary .js files on heroku. Everything works fine. Now, I don't want to send my users to "myappname.herokuapp.com", so I plan to use my own website to store the .html file, but when the user taps "submit" on my HTML form, I want to execute the Herok NodeJS code.
Here is what the html looks like
<script>
const form = document.querySelector("form");
form.addEventListener("submit", async (e) => {
e.preventDefault();
try {
displayStatus("processing...");
const request = new Request("/file-upload", {
method: "POST",
body: new FormData(form),
});
const res = await fetch(request);
const resJson = await res.json();
displayResult(resJson.result);
} catch (err) {
displayStatus("an unexpected error");
console.error(err);
}
});
function displayResult(result) {
const content = `Your ID: ${result.id}`;
displayStatus(content);
}
function displayStatus(msg) {
result.textContent = msg;
}
</script>
How can I call this "/file-upload" from my HTML that is located on "mywebsite.com/index.html" while the actual NodeJS logic runs on "myappname.herokuapp.com"
I've tried to replace the "/file-upload" with "myappname.herokuapp.com/file-upload" but it doesn't work.
Again, the goal is to use what I have on Heroku, but not have the users go to "myappname.herokuapp.com" instead they should go to "mywebsite.com/index.html"
Thank you
Actually, replacing "/file-upload" with "myappname.herokuapp.com/file-upload" did the trick. The only issue is my "const request = new Request" request returning an error all the time, but Heroku logs shows a successful execution of "file-upload"

How to use a Javascript file to refresh/reload a div from an HTML file?

I am using Node JS and have a JS file, which opens a connection to an API, works with the receving API data and then saves the changed data into a JSON file. Next I have an HTML file, which takes the data from the JSON file and puts it into a table. At the end I open the HTML file in my browser to look at the visualized table and its data.
What I would like to happen is, that the table (or more specific a DIV with an ID inside the table) from the HTML file refreshes itself, when the JSON data gets updated from the JS file. Kinda like a "live table/website", that I can watch change over time without the need to presh F5.
Instead of just opening the HTML locally, I have tried it by using the JS file and creating a connection with the file like this:
const http = require('http');
const path = require('path');
const browser = http.createServer(function (request, response) {
var filePath = '.' + request.url;
if (filePath == './') {
filePath = './Table.html';
}
var extname = String(path.extname(filePath)).toLowerCase();
var mimeTypes = {
'.html': 'text/html',
'.css': 'text/css',
'.png': 'image/png',
'.js': 'text/javascript',
'.json': 'application/json'
};
var contentType = mimeTypes[extname] || 'application/octet-stream';
fs.readFile(filePath, function(error, content) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
});
}).listen(3000);
This creates a working connection and I am able to see it in the browser, but sadly it doesn't update itself like I wish. I thought about some kind of function, which gets called right after the JSON file got saved and tells the div to reload itself.
I also read about something like window.onload, location.load() or getElementById(), but I am not able to figure out the right way.
What can I do?
Thank you.
Websockets!
Though they might sound scary, it's very easy to get started with websockets in NodeJS, especially if you use Socket.io.
You will need two dependencies in your node application:
"socket.io": "^4.1.3",
"socketio-wildcard": "^2.0.0"
your HTML File:
<script type="module" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js"></script>
Your CLIENT SIDE JavaScript file:
var socket = io();
socket.on("update", function (data) { //update can be any sort of string, treat it like an event name
console.log(data);
// the rest of the code to update the html
})
your NODE JS file:
import { Server } from "socket.io";
// other code...
let io = new Server(server);
let activeConnections = {};
io.sockets.on("connection", function (socket) {
// 'connection' is a "magic" key
// track the active connections
activeConnections[socket.id] = socket;
socket.on("disconnect", function () {
/* Not required, but you can add special handling here to prevent errors */
delete activeConnections[socket.id];
})
socket.on("update", (data) => {
// Update is any sort of key
console.log(data)
})
})
// Example with Express
app.get('/some/api/call', function (req, res) {
var data = // your API Processing here
Object.keys(activeConnections).forEach((conn) => {
conn.emit('update', data)
}
res.send(data);
})
Finally, shameful self promotion, here's one of my "dead" side projects using websockets, because I'm sure I forgot some small detail, and this might help. https://github.com/Nhawdge/robert-quest

invoke node.js server-side service in angularjs. getting following error. Error: [$injector:nomod] Module ‘angularjsNodejsTutorial’ is not available

This is the error: Error: [$injector:modulerr] Failed to instantiate module angularjsNodejsTutorial due to:
Error: [$injector:nomod] Module ‘angularjsNodejsTutorial’ is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.” exception. from browser or postman when I hit localhost:3000/dirPath then I get the data back but not through this html file.
//here are the files: index.html, app.js(angularjs) and index.js(node)
//index.html
<!DOCTYPE html>
<html ng-app="angularjsNodejsTutorial">
<head>
<title>Integrating AngularJS with NodeJS</title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
<script src="../node_modules/angular-route/angular-route.min.js"></script>
</head>
<body >
<div ng-controller="myController">
<ul >
<li> The Files Are: {{data}}</li>
</ul>
</div>
<script src="../public/javascripts/app.js" type="text/javascript"></script>
<script src="../node_modules/angular-route/angular-route.js"></script>
</body>
</html>
//(AngularJS Client-Side)app.js
var app = angular.module('angularjsNodejsTutorial',['ngRoute']);
app.controller('myController', function($scope, $http) {
$scope.data = [];
var request = $http.get('/dirPath');
request.success(function(data) {
console.print("The files from this directory are:", data);
$scope.data = data;
});
request.error(function(data){
console.log('Error: ' + data);
});
});
//Server-side node.js index.js file
var express = require('express');
var router = express.Router();
var path = require('path');
/* GET home page. */
router.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
router.get("/dirPath", function(req, res) {
var fs = require("fs");
var dir = '/Users/swapnil/Documents/Test';
fileList = [];
var files = fs.readdirSync(dir);
for(var i in files){
if (!files.hasOwnProperty(i)) continue;
var name = dir+'/'+files[i];
if (!fs.statSync(name).isDirectory()){
fileList.push(name);
}
}
return res.send(fileList);
});
module.exports = router;
I think you are over thinking your route process, this will do the basics:
function config ($routeProvider, _) {
$routeProvider.
when('/Order', {
templateUrl: '../modern/sections/views/view.html',
controller: 'Controller as ctrl',
caseInsensitiveMatch: true,
resolve: {
data: function(Factory){
var view = window.location.href.match(/OrderID=(.*)#/) || 'undefined';
if(Id === 'undefined'){
return Factory.createOrder();
}else{
return Factory.currentOrder(OrderId[1]);
}
}
}
})
.otherwise({
redirectTo: '/'
});
}
FYI: Resolve calls Factories where i have services setup to get my API data.
Sorry if this is not direct, i copied this over from a current working project i have.
Resolved the issue by exposing the server side functionality as a RESTful API instead of node and modified my controller by adding appropriate header info for content type and implemented CORS filter on the server side.
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers",
"X-Requested-With,Origin,Content-Type, Accept");
filterChain.doFilter(request, response);
}
Thanks everyone for taking time to look at my issue and offering help. Appreciate.
Check your modules and make sure they are being loaded appropriately. It's a very common error when you start out. Check your html file and make sure all the modules names are spelled correctly.
If your modules are sharing logic it's common to accidentally miss spell the module name. This case I normally copy and past it over.
Also look at your logic behind the module and make sure you are declaring it properly.

Favicon.ico not being requested

Is there a way to setup an icon for an HTML page using only 'http' and 'fs' modules for node.js (without express)?
I have index.html, main_page.css and favicon.ico files in my directory.
When the client connects, it receives index.html:
<!DOCTYPE html>
<html>
<head>
<title>Site</title>
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="css/main_page.css" />
</head>
<body>
</body>
</html>
Then the server receives a request for .css file and sends it to the client.
The page is styled as it should be, so there is no reason to show the code.
The question is, why does the client ask for .css file by itself and doesn't ask for .ico?
This is the code on the server, that serves the files:
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
switch (req.url) {
case '/': {
get_file('index.html', res);
break;
}
case '/css/main_page.css': {
get_file('css/main_page.css',res);
break;
}
case '/favicon.ico': {
get_file('favicon.ico', res);
break;
}
default: {
res.statusCode = 404;
res.end("Not found");
}
}
}).listen(8081);
function get_file(path, res) {
//dont mind my ROOT ;0
fs.readFile(ROOT + path, function(err, content) {
if(err) {
console.log(err.message);
} else {
console.log(path);
res.end(content);
}
})
}
The favicon.ico file gets cached by Chrome, so once it has been requested once, it will not be requested again until the cache expires. To generate a new request for favicon.ico you will need to refresh the page in Chrome.

node.js server, displaying HTML file which has jqGrid plugin included.

I have a simple HTML file which includes jqGrid plugin. I am using jqGrid plugin to have a tree grid in my HTML page.
Now, I am trying to host this HTML file in node.js server. My server.js looks like this
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = '.' + request.url;
console.log('filePath : '+filePath);
if (filePath == './')
filePath = './tree.html';
var extname = path.extname(filePath);
console.log('extname : '+extname);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
} else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
} else {
response.writeHead(404);
response.end();
}
});
}).listen(8125);
So far, I am able to display my HTML content in browser [http://localhost:8125/]
Part of my HTML(tree.html) file looks like this
jQuery("#treegrid").jqGrid({
url: 'tree.json',
datatype: 'json',
//mtype: 'GET',
colNames: [/* "ID", */"Col 1", "Col 2",.. ],
colModel: [/* {
name: 'id',
index: 'id',
width: 1,
hidden: true,
key: true
}, */{ ...
If you can notice, I have specified 'tree.json' as URL attribute to load the tree grid. That is just reading a static file to load the tree grid with sample data.
Problem : Now, when I try to access my HTML file using [http://localhost:8125/]
I get an 404 Not Found error for [http://localhost:8125/tree.json]
Quick Solution : I can specify the relative path of the file 'tree.json' and it works.
Both my HTML file tree.html and tree.json are in the same directory (/tree) and I start my node.js server from command prompt (terminal) like this
tree> node server.js
I would like to know where I can place my tree.json in order to make my HTML work as intended.
Please feel free to ask any clarification.
Thanks in advance
You use the line
var filePath = '.' + request.url;
in your code which seems a little strange. Probably in case of request of 'tree.json' you will have .tree.json as the value of filePath instead of ./tree.json which you probably want to have. I think you should fix the code here.
Moreover it would be good to set 'application/json' as the value of contentType variable in case of .json extension in the same way like you set 'text/javascript' and 'text/css' for '.js' and '.css' files.