Node JS serving HTML pages Express - javascript

I have a multiplayer game where a server connects two clients to play against each other. It works well. However, now I want to add a welcome page where they add their username. I need to send this username to the server. However, the problem is, when loading the welcome page it makes a connection to the server (which is good). But, when i want to load the next page using
location.href = "index.html"
it is not working. In fact, it disconnects from the server and does not reconnect. How do I load multiple files after a player hits a button? And how do I keep these files under the same "client" instance? (without disconnecting). Thank you.

Since you have no code, let me take a stab at it. To expand on what #anderson said, Make sure you have your static files available to your app via something like
const staticCont = express.static(__dirname + "/public");
Where "public" is, is the folder directory of all your static files. This way, any link in your app(on the front end) that requires loading of whatever files, will be available to you.
Next, assuming this was done, also, assuming your game is on a singular page, lets say "mygame.html", if you want to load another html or other content into this page without losing/navigating away from "mygame.html", then on the users button press you are going to need AJAX to load in content.
as an example:
Create a dummy div that will hold your loaded content, lets call it
<div id="usrBioWrapper"></div>
Then say you have a button on your app that fetches a users bio.
Lets call this button
<button id="usrBio">Get user bio</button>
and the html you want to load is called usrBioPage.html, then you'd need something like:
$('#usrBio').on('click', function(){
$('#usrBioWrapper').load(' usrBioPage.html ');
});
Thats it. When the user clicks the button, it will load your content in that div. BUT remember, you must set the public directory in your app.js(backend node side) else it wont work.
hope this helps

Did you public your index.html file in Node js, to make sure your browser can access the file?

Related

HTML 5 anchor tag download incomplete file?

I am using angular and ASP.NET Web API to allow users to download files that are generated on the server.
HTML Markup for download link:
<img src="/content/images/table_excel.png">
<a ng-click="exportToExcel(report.Id)">Excel Model</a>
<a id="report_{{report.Id}}" target="_self"></a>
The last anchor tag is there to serve as a place holder for an automatic click event. The visible anchor calls the exportToExcel method to initiate the call to the server and begin creating the file.
$scope.exportToExcel = function(reportId) {
reportService.excelExport(reportId, function (result) {
var url = "/files/report_" + reportId + "/" + result.data.Model.fileName;
var dLink = document.getElementById("report_" + reportId);
dLink.href = url;
dLink.setAttribute('download', result.data.Model.fileName);
dLink.click();
});
}
The Web API code creates an Excel file. The file, on the server is about 279k, but when it is downloaded on the client it is only 7k. My first thought was that the automatic click might be happening before the file is completely written. So, I added a 10 second $timeout around the click event as a test. It failed with the same result.
This seems to only be happening on our remote QA server. On my local development server I always get the entire file back. I am at a loss as to why this might be happening. We have similar functionality where files are constructed from a database blob and saved to the local disk for download. The same method is employed for the client side download and that seems to work fine. I am wondering if anyone else has run into a similar issue.
Update
After the comment by SilentTremmor we think it actually may be IIS or some sort of Sever issue. Originally, we didn't think it could be, but after some digging it may be. It seems the instance of the client code is only allowing 7k of data to be downloaded. It doesn't matter what we try to download the result is always the same.
It turns out the API application was writing the file to a different instance of our application. The client code had no idea and was trying to download a file that did not exist. So, when the download link was creating the file it was empty, thus the small file size.

How to make Angular.js routing urls into dynamic, so urls won't be long

So while I'm making my first angular app, I see that the urls change for different pages, which is what's suppose to happen. So say I click a button and this
http://localhost:63342/angularSPA/app/view2/view2.html
changes to
http://localhost:63342/angularSPA/app/view2/view3.html.
What will the users see once I upload this all to something like heroku or my own domain. Everytime I route them to a page, will they see this long URL and will it change everytime I click a button or something?
you only need to upload what is inside the app folder. so this:
http://localhost:63342/angularSPA/app/view2/view2.html
will become this:
http://localhost:63342/view2/view2.html
if you put your index.html file in your root/app directory it will get even shorter:
http://localhost:63342/index.html
However, you can use a number of directives to achieve page changes without changing the url.
https://docs.angularjs.org/api/ng/directive/ngSwitch
https://docs.angularjs.org/api/ngRoute/directive/ngView
https://docs.angularjs.org/api/ng/directive/ngShow
https://docs.angularjs.org/api/ng/directive/ngHide
https://docs.angularjs.org/api/ng/directive/ngIf
You could, but I don't know why you would, have your entire site be under index.html.
However, that means that the user's browser will have to load ALL of your 'stuff' before displaying the single page app. It also means you won't be able to use the power of routing.
Also, angular adds # in there.
Here is a good ui-router tutorial.
https://scotch.io/tutorials/angular-routing-using-ui-router

Change path of iframe on page change

I have two websites www.mywebsite.com and www.otherwebsite.com. I use iframe to redirect mywebsite.com to otherwebsite.com. Is there a to change the path of url on page change. For example when a link otherwebsite.com/contact.html is clicked the frame adds /contact.html to mywebsite.com making it www.mywebsite.com/contact.html. I tried adding the code below to the page but it doesn't seem to work on the frame.
history.pushState(null, "A new title!", "contact.html")
what you trying to do is not possible without a server side language (for example php).
this is because you need to define filename as a variable for your frame to load it with another site.
but you can do it at some static way like making the real contact.html and code it with a frame that shows contact.html for another side ... but i dont think that would be a dynamic way without any server side coding...

How can I *locally* save an .html file generated by javascript (running on a *local* .html page)?

So I've been researching this for a couple days and haven't come up with anything conclusive. I'm trying to create a (very) rudimentary liveblogging setup because I don't want to pay for something like CoverItLive. My process is: Local HTML file > Cloud storage (Dropbox/Drive/etc) > iframe on content page. All that works, and with some CSS even looks pretty nice despite the less-than-awesome approach. But here's the thing: the liveblog itself is made up of an HTML table, and I have to manually copy/paste the code for a new row, fill in the timestamp, write the new message, and save the document (which then syncs with the cloud and shows up in the iframe). To simplify the process I've made another HTML file which I intend to run locally and use to add entries to the table automatically. At the moment it's just a bunch of input boxes and some javascript to automate the timestamp and write the table row from the input data.
Code, as it stands now: http://jsfiddle.net/LukeLC/999bH/
What I'm looking to do from here is find a way to somehow export the generated table data to another .html file on my hard drive. So far I've managed to get this code...
if(document.documentElement && document.documentElement.innerHTML){
var a=document.getElementById("tblive").innerHTML;
a=a.replace(/</g,'<');
var w=window.open();
w.document.open();
w.document.write('<pre><tblive>\n'+a+'\n</tblive></pre>');
w.document.close();
}
}
...to open just the generated table code in a new window, and sure, I can save the source from there, but the whole point is to eliminate steps like that from the process.
How can I tell the page to save the generated code to a separate .html file when I click on the 'submit' button? Again, all of this happens locally, not on a server.
I'm not very good with javascript--and maybe a different language will be necessary--but any help is much appreciated.
I suppose you could do something like this:
var myHTMLDoc = "<html><head><title>mydoc</title></head><body>This is a test page</body></html>";
var uri = "data:application/octet-stream;base64,"+btoa(myHTMLDoc);
document.location = uri;
BTW, btoa might not be cross-browser, I think modern browsers all have it, but older versions of IE don't. AFAIK base64 isn't even needed. you might be able to get away with
var uri = "data:application/octet-stream,"+myHTMLDoc;
Drawbacks with this is that you can't set the filename when it gets saved
You cant do this with javascript but you can have a HTML5 link to open save dialogue:
<a href="pageToDownload.html" download>Download</a>
You could add some smarts to automate it on the processed page after the POST.
fiddle : http://jsfiddle.net/ghQ9M/
Simple answer, you can't.
JavaScript is restricted to perform such operations due to security reasons.
The best way to accomplish that, would be, to call a server page that would write
the new file on the server. Then from javascript perform a POST request to the
server page passing the data you want to write to the new file.
If you want the user to save the page to it's file system, this is a different
problem and the best approach to accomplish that, would be to, notify the user/ask him
to save the page, that page could be your new window like you are doing w.open().
Let me do some demonstration for you:
//assuming you know jquery or are willing to use it :)
var html = $("#tblive").html().replace(/</g, '<');
//generating your download button
$.post('generate_page.php', { content: html })
.done(function( data ) {
var filename = data;
//inject some html to allow user to navigate to the new page (example)
$('#tblive').parent().append(
'Check your Dynamic Page!');
// you data here, is the response from the server so you can return
// your new dynamic page file name here.
// and maybe to some window.location="new page";
});
On the server side, something like this:
<?php
if($_REQUEST["content"]){
$pagename = uniqid("page_", true) . '.html';
file_put_contents($pagename, $_REQUEST["content"]);
echo $pagename;
}
?>
Some notes, I haven't tested the example, but it works in theory.
I assume that with this the effort to implement it should be minimal, assuming this solves your problem.
A server based solution:
You'll need to set up a server (or your PC) to serve your HTML page with headers that tell your browser to download the page instead of processing the HTML markup. If you want to do this on your local machine, you can use software such as WAMP (or MAMP for Mac or LAMP for Linux) that is basically a web server in a .exe. It's a lot of hassle but it'll work.

Strategy Issue: Flat / Static Pages within a RESTful app

I'm using Backbone.js to connect to a Django backend via tastypie. I've got things figured out for my dynamic content, but I am wondering what to do about my FAQ / About / Contact pages. Because I want to have an uninterrupted user experience, no waiting for the page to load in between links, I'm wondering where to load the data for these flat pages from.
I don't want to overarchitect here, because these are brochure pages with non-dynamic content. In short, layout is important, and they don't need a CMS.
So do I have the pages already in my main index.html, and just show them when needed? This seems dirty to me.
Do I have Django store the html for these pages in a Textarea set up to accept html, and spit the html out as JSON through tastypie when needed? Ugh, that sounds dirty to me too.
Or a hybrid where django only spits out the relevant data to fill in the html that's already defined in my index.html-- This sounds correct, but like way too much work, I don't want to define db models for pages that as I've said, don't need a CMS.
I'm hoping I'm way off base with all these approaches, and you have something much better to solve my dilemma.
Your first idea of including them in the main index.html and showing them as needed seems quite reasonable, but has a couple drawbacks:
Your index page is heavier and thus slower to load than it needs to be
Your brochure pages aren't logically separated in your codebase
You can fix both of these by having the HTML for them loaded dynamically after the index.html loads. You'd still use the same client-side code to show the pages when the user clicks to them as if it were embedded in the main HTML file, but instead of including the HTML in the initial index.html file...
<div id="faq-page">
<h1>FAQ</h1>
...
</div>
have blank divs and an event to load them through AJAX after the main page has rendered. I'm not sure if you're using jquery, but if so, the code would look like this
<div id="faq-page"></div>
<script>
$(function() {
$("#faq-page").hide() // ensure it doesn't display too early
.load("/include/faq.html"); // async load the content from server
});
</script>
Now when the user hits the FAQ link in your app, the page will appear as fast as possible. If the page has had time to load (normally) it will show up instantly. If they happen to hit the link before it's loaded, it will show up as soon as the server responds.
You set up /include/faq.html however you'd like on the server side.

Categories