Node js - socket.io - Linked Stylesheet not loading... port issue? - html

I have a working chat application ( tutorial here : https://www.youtube.com/watch?v=QISU14OrRbI ) hooked to mysql instead of mongodb.
All of my code in a paste, minus the css : http://pastebin.com/j5FLZyFP
I have always been able to link to a css file via the link element in the DOM head. I am wondering why this approach doesn't work in my example and if it has anything to do with which ports i am using. The server that serves the index.html page is running on port 8080, while my sockets server is running on port 9000. Should I be using the same port for both of them? If so, how do I do that?
Below are screenshots of my browser # 127.0.0.1:8080
I need 10 reputation to post more than 2 links, slap my wrist I suppose - https[colon][slash][slash]imgur[dot]com[slash]a[slash]22Vv5
I get served the page, but i am forced to press ESC to stop the main.css from getting transferred. Then the remaining requests come through. don't be concerned about inject.js, it represents the Wappalyzer extension and I have tried the example with Wappalyzer disabled.
Adding my CSS to a style tag works and isn't too much trouble to implement in my case, but it would be nice to solve this problem. Thanks.

Kamran Adil in the comments has answered this well. See linked question: Node.js - external JS and CSS files (just using node.js not express)
this worked just fine adding a new condition to test the request
var param = 'main'; /* Stylesheet file name */
if(req.url.indexOf('.css') != -1) {
fs.readFile('./styles/'+ param +'.css', function (err, data) {
if (err) { console.log(err); }
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data);
res.end();
});
}

Related

Create Action For Running Nodejs inside HTML

I am new at Node.js
I create a server with node.js I have file like this:
Server.js
Client.js
Index.html
Server configuration is okay. But Inside HTML, I would like to link or an action to run client.js
At HTML, usually we use Link to link a page.
or
run npm with node client.js to run client.js
How I do it at html to run client.js, so if we click a link - client.js will run (the action is same like we do for run at npm node client.js)?
EDIT :
Oke, it looks like difficult to run client.js inside html with click. I changed my question.
I run node.js. And I open a browser (with anything extension html or js) and I would like to run client.js with a click. How do I do that?
I have never hear of such thing.
But I think, if you want to change something in server through frontend, http ajax is a good way.
But according to my acquaintance, when server accept a request from frontend, in a general way,it will run some code,such as function, but not js file.
You could run js file through child_process, it is a module in node, which use to call the shell in your system.
PS, shell.js is a better way if you want to call the shell in nodejs.
see this. https://github.com/shelljs/shelljs
Some server side programming environments work on the basis of having a program, in a file, for each URL that needs to be handled.
Node.js does not work that way.
You write a single server program which handles all the requests and which examines the URL of each one to determine what to do.
const http = require('http');
const server = http.createServer((req, res) => {
console.log(req.url);
if (req.url == "/") {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("The homepage");
} else if (req.url == "/client.js") {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("Whatever you want to do for a request for client.js");
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end("Not found");
}
});
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);
While you might store some code in client.js, that filename wouldn't be mentioned to the client. The server would just load it like any other module and then conditionally call functions from it.

Node.js: My HTML requires an image

See, I was training with Node (and TS btw), and tried to do a trivial server with multiple request/response options. But I have a problem I don't know how to solve without using Express (at least for now I don't want to use it).
I have a HTML file which requests an image file. While in the IDE, everything looks like it's going to work, but when the server is running, the image cannot be found. It's kind of obvious why: The HTML makes a request the server doesn't know how to handle. Thing is, I thought the document could refer to other files without the need of talking to the server.
What is an elegant and working solution for my problem?
Thanks in advance.
import * as http from 'http'
import * as fs from 'fs'
fs.readFile('doc/kmCNHkq.jpg', function (err, data) {
let binaryimg = new Buffer(data).toString('base64');
if (err) throw err;
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'image/jpeg'});
res.end(data);
console.log("Delivered the jpeg");
}).listen(8000);
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(binaryimg);
console.log("Delivered base64 string");
}).listen(8124);
console.log("Unless bug, both servers are listening");
});
fs.readFile('doc/index.html', function(err, data) {
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data)
}).listen(80);
console.log("HTML server is running")
})
(main.ts; Targets ES6)
<html>
<head>
</head>
<body>
<img src="doc/kmCNHkq.jpg"/>
</body>
</html>
(index.html)
Observation: I used to leave the HTML file in '../doc/' and resources on '../img/' however it seems that the HTML uses relative paths, so I copied the image into HTML's folder. If the solution also made it so I could leave the resources on their's respective folders it would be much appreciated.
#Edit:
Now I'm using this switch/case request handler. Working as expected, the HTML's request for the image is interpreted as a normal request (which may not end up scaling well, idk, but screw it). Thanks a lot!
import * as http from 'http'
import * as fs from 'fs'
var stream: fs.ReadStream,
folder = __dirname.substr(0, __dirname.length - 3);
http.createServer(function(req,res) {
switch (req.url){
case('/jpeg'):
stream = fs.createReadStream(folder + 'img/kmCNHkq.jpg');
stream.pipe(res);
console.log("Delivering the jpeg");
break;
case('/base64'):
fs.readFile('img/kmCNHkq.jpg', function (err, data) {
let img64 = new Buffer(data).toString('base64');
if (err) throw err;
res.end(img64);
console.log("Delivered base64 string");
})
break;
case('/html'):
stream = fs.createReadStream(folder + 'doc/index.html');
stream.pipe(res);
console.log("Sending the docs");
break;
default:
console.log("Shit happens");
}
}).listen(80)
(main.ts)
<html>
<body>
<img src="jpeg"/>
</body>
</html>
(index.html)
Short answer:
You won't be able to refer to specific resources on the server (such as your image) unless your server knows how to respond to those requests for that content. It looks like you can probably make your example work easily immediately though by changing the image src to just http://localhost:8000 though.
Longer answer:
Using 'doc/kmCNHkq.jpg' as the src for your image tells your browser that when it loads the page, it should go to the server it got the page from, and ask it for the 'doc/kmCNHkq.jpg' resource. If you specify a full URL including the protocol (the http://) then it will be absolute, instead of relative, so you can request from a different server than the one that served the page.
The servers that you've written don't actually look at the path of the file that's requested though (req.url), and actually they just always return the same content. If you connect to http://localhost:80 (the third server you've created above), and do request that jpg you'll still just get given the same HTML data of the page, because it just runs the two lines in your createServer call at the end of your example. You have written a server that always returns the image however above (the first server), just running on a different port, which is why the above solution works.
Just using that existing server is the simplest solution. The far more conventional approach though is to have just a single HTTP server running on a single port (instead of the 3 you have) and to use req.url to decide what data to return.
Traditionally for static content that means mapping a requested path directly onto the layout of the files on disk, so that requesting doc/abc.jpg looks for a doc folder in the server's directory, and returns the data from abc.jpg therein. That's not required necessarily at all though, and your server can interpret those paths however you like, to return content from anywhere.
(Note than none of this is really anything to do with TypeScript, or even much to do with Node.js. This is really just the essentials of how HTTP servers and browsers interact, and it would be almost identical with any other backing technology. I'd take a look more into the general HTTP and browser details if you're looking to get more background on this.)

HTML link to either local network or domain name

In my web page, I want to link to another web server in my local network.
I use <a href="192.168.1.111:8080/index.jsp">to do this when I am in local network. However, when I access the website outside the local network, I need to use domain name. <a href="mydomain.com:8080/index.jsp">
How can I do this in same page of code if I would access it from both LAN and WAN.
Well, if it's an option, the easiest way to avoid this issue is using relative links. For example, if you're linking to another page on the same website, your link will always work if it's something like "../directory/some-web-page.html" rather than a full link with http included.
Otherwise, if you're linking to a completely different site, you could check whether your page exists on the local server using a very simple JQuery ajax request. If it doesn't exist, then assume you are not signed in to the same network and insert your remote domain name.
As discussed here, your simple ajax request can just fetch the HEAD of the locally hosted page, that way you're not fetching too much data and only confirming whether it exists. Your code could be something like this:
$( document ).ready(function(){
$.ajax({
url: 'path/to/your-file.html',
type: 'HEAD',
success: function() {
// page exists
// replace the href attribute with local host link
document.getElementById('your-link').setAttribute('href', 'path/to/your-file.html');
},
error: function() {
// page does not exist
// do nothing, so your link sends user to remote site
}
});
});
And then, in your HTML, just include the link to your remote site like so:
<a id="your-link" href="yourremotesite.com">This is a link</a>
This should work on both a local and remote server without having to change the code.
EDIT:
I had to jump out of bed because another answer was just nagging at me...
You can also try accessing window.location.host or window.location.hostname and testing that in an if-statement to determine whether your page is on the local host or remote server.
Anyway, I hope one of these solutions helps. Good night and good luck!
HTML:
link
javascript:
<script>
window.onload=myFunction;
function myFunction() {
var x = document.domain;
var a = document.getElementById('link');
a.href = x + "/index.jsp";
}
</script>

HTML5 Offline Functionality Doesn't Work When Browser Restarted

I am using the offline HTML5 functionality to cache my web application.
It works fine some of the time, but there are certain circumstances where it has weird behaviour. I am trying to figure out why, and how I can fix it.
I am using Sammy, and I think that might be related.
Here is when it goes wrong,
Browse to my page http://domain/App note: I haven't included a slash after the /App
I am then redirected to http://domain/App/#/ by sammy
Everything is cached (including images)
I go offline, I am using a virtual machine for this, so I unplug the virtual network adapter
I close the browser
I reopen the browser and browse to my page http://domain/App/#/
The content is showing except for the images
Everything works fine if in step #1 I browse to http://domain/App/ including the slash.
There are some other weird states it gets into where the sammy routes are not called, so the page remains blank, but I haven't been able to reliably replicate that.
??
UPDATE: The problem is that the above steps caused problems before. It is now working when I follow the above steps, so it is hard to say what is going on exactly. I am starting from a consistent state every time because I am starting from a snapshot in a VM.
My cache manifest looks like this,
CACHE MANIFEST
javascripts/jquery-1.4.2.js
javascripts/sammy/sammy.js
javascripts/json_store.js
javascripts/sammy/plugins/sammy.template.js
stylesheets/jsonstore.css
templates/item.template
templates/item_detail.template
images/1Large.jpg
images/1Small.jpg
images/2Large.jpg
images/2Small.jpg
images/3Large.jpg
images/3Small.jpg
images/4Large.jpg
images/4Small.jpg
index.html
I'm running into a similar issue as well.
I think part of the problem is that jquery ajax is misinterpreting the response. I believe sammy is using the jquery to make the ajax calls, which is leading to the errors.
Here's a code snippet i used to test for this (though not a solution)
this.get('#/', function (context) {
var uri = 'index.html';
// what i'm trying to call
context.partial(uri, {});// fails on some browsers after initial caching
// show's that jquery's ajax is misinterpreting
// the response
$.ajax({
url:uri,
success: function(data, textStatus, jqXHR){
alert('success')
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert('error')
if(jqXHR.status == 0){ // this is actually a success
alert(jqXHR.responseText);
}else{
alert('error code: ' + jqXHR.status) // probably a real error
}
}
});

Mootools request - cannot make the examples work

I've downloaded the examples for both the Request and Request.HTML and cannot make either work. I unzipped them to a folder and browsed to their index.html to execute them as is, but the response is always "The request failed." with no clues as to why.
I've played around with them with different permutations and can get the request to complete but it always fails. Is there any way to get a reason for failure? I've tried three different browsers turned off my firewall, used relative and absolute file references but nothing works. Am I missing something glarringly obvious? I'd post the code, but it is the examples exactly as is...
Any help would be awesome.
Cheers,
Justin.
If I'm remembering correctly, AJAX requests in most browsers cannot be done via the local file system - you'll need an actual web server like Apache going. In Windows, XAMPP will get you up and running with Apache in minutes.
Most any webserver should work. It's just that your filesystem doesn't "respond" to browser requests the way a web server does:
ajax requests that are executed
locally (against the file system)
don't work well because the ajax logic
is looking for a state change and a
server response, neither of which are
provided by your file system
-- http://forum.mootools.net/viewtopic.php?id=5009
The XMLHttpRequest object can handle more than just HTTP requests supposedly, but at least in mootools, it's not meant to. And "file:///..." is not an HTTP request. It's just taking a file from your file system and displaying it in the browser.
So the good news is: any web browser, including even a bare-bones one running on your local machine, should work fine :)
Brilliant!! Thanks very much! I uploaded it to my nearest webserver and sure enough it works.
I did try doing some Ajax calls directly from my filesystem without any javascript libraries - using XMLHttpRequest() - and it worked fine, so this does seem like a strange limitation. Can I be sure this will always work from any webserver, however basic? It's just that this project I'm working on is going to be using multiple hosting environments, mainly just plain HTML type sites for the client enviornments of which I'll have no control... Is there a minimum specification?
Cheers ;)
The XMLHttpRequest() succeeds cause there's nothing wrong with making the local call. it's just different and the problem is in the buggy mootools isSuccess function.
You gotta override it the Request options. Here's how jquery does it
// Determines if an XMLHttpRequest was successful or not
httpSuccess: function( xhr ) {
try {
// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
return !xhr.status && location.protocol === "file:" ||
// Opera returns 0 when status is 304
( xhr.status >= 200 && xhr.status < 300 ) ||
xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
} catch(e) {}
return false;
},