Clientside URL Routing - javascript

Looking at turning my ASP MVC app into pure JS/Html however its not just a 1 page app, it has a couple of pages, but each one has alot of ajax and events.
Anyway currently my urls on ASP MVC are like:
/login
/admin/{action}/{adminId}
/posts/{posterId}
/picture/{pictureId}
So that is all nice and simple and easy to see what you are doing in the url, you also get correct back button behaviour. So trying to adopt this sort of thing to a pure JS/Html approach seems to bit either very tough or impossible. I dont need an exact match but I was hoping to do something like:
http://localhost/myapp/posts/10
Then that would somehow be able to route the actual request to http://localhost/myapp/posts.html with the variable exposed. Now I am pretty sure this is impossible as when the above is entered into the browser it is going to attempt to look in a directory called posts and look for 10, which wont exist.
Now I have seen Crossroads and LeviRoutes and a few other similar technologies, however they seem to rely upon the hashbang method, which some people like others hate. Is there any way around this? If not can anyone point to any good tutorials on how to use these frameworks, as each seems fairly light on documentation.

There's no workaround for not using hash. HTML5 History API isn't available on IE and Opera yet. If your application is targeting very specific platform, then you can use History API instead of hash. However, History API is inconsistent across browsers. You can read it here: http://www.battlehorse.net/page/2011/02/12/html5history.htm
If you choose to use History API, it would be easy. You can use whatever routing strategy you want in ASP.NET MVC, then just match this strategy in JavaScript. You can read more about History API here: https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history
If you choose to use hash, you need to do make some requests into AJAX requests:
Determine if a request is done via AJAX:
if GET/posts/{action}/{id} is by AJAX, serve the original content
if it's not by AJAX, redirect the user to /#!/posts/{action}/{id}.
Handle client side hash by requesting for the right content:
When the hash is changed to #!/posts/{action}/{id}, GET /posts/{action}/{id} via AJAX and replace the content with the new one from the server.
Intercept form.onsubmit event:
Whenever a form is trying to submit to /posts/{action}/{id}, cancel it and use AJAX to post and then replace the content with the new one from the server.
Now your app should work like a one page app.

There is no real way around hashbangs if you wish to keep it clientside and cross browser compatible.

Related

Sending safely JSON to server via an HTML form page

I have an html page that has a form and is communicating to a server via JSON requests, when loading (e.g. in order to remember user's previous answers) and when submit button is pressed (e.g. in order to save his new answers). Every user has a specific user_id that is located as an attribute in the url of the website. I have only HTML pages, CSS and Javascript that makes some simple functions, as well as received and sends the requests.
The problem is that the server needs an api-key for the request to happen, that I need to be kept hidden, but instead is easily discovered when the user sees the source code. I want this specific line to be hidden, but I guess this is not possible without any backend in the game.
I would like to know the easiest and fastest way to get from this state (just frontend, where every piece of information in the source code is totally insecure) to another where the api-key (at least) is not on the open.
I guess the solution is to use a server for that part but I need suggestion on the easiest transition from my code to another. I tried to use GWT, as I am a bit more familiar with JAVA backend application (but not with GWT), but seems like a big trouble, where I need to change my HTML, my Javascript and also the CSS that I have may not be useful, as well as I face a lot of problems when trying to read my parameters.
I know that it is not the best way but I do not have a lot of time to make it work, so sorry if it seems lazy (I am new to this type of programming), but I haven't found anything helpful and I cannot study for 2 weeks in order to be able to begin implementing it.
Is node.js (which is Javascript and I already have implemented the request sending/receiving in this language) easier than GWT for that matter? Will my sensitive data be secure in that way? I would be grateful if there was a similar sample, that I could start using for my implementation, as I haven't find anything that is specifically helpful for my situation.
Thanks in advance!
NodeJs is not javascript, NodeJs is specific javascript "interpreter" whose is purpose is mainly to be executed server-side. If you have an HTML page, it is likely to be loaded in a web browser (client-side), so not in a NodeJs environnement.
Everything that is hard-coded in the javascript of you web page is visible from the client, there is no way around that. So yes, you need some server-ish thing somewhere.
If you are not to manage a server by yourself or via PaaS, you can go for a serverless architecture. For instance, If you consider AWS which I know the most, you can easilly add some user management to your web page using Aws Cognito User Pool. Once a user is connected and have the good permission, he can be granted access to some other resources via a JWT token that you send along with your request.

What happens when you enable the html5 mode in mode in angularjs?

What actually happens when you enable the html5 mode ? This might go back to the point how routing takes place in single page applications
What I perceived before(it may be wrong) : Looking at the dirty url in the angularjs application I always assumed it being url fragment to which different views are bind for different fragments. So in short we already have all the pages and a particular fragment is being displayed for a particular url .
Now in order to remove the hash you have to set html5mode true and you have to tell the server to return the index page for every request other than your apis . Kinda like
app.get('/ap1',some);
//more apis
*
*
*
//in the end
app.get('*' ,(req,res,next) => req.sendFile('index.html'));
Shouldn't the request go the server and the page be reloaded everytime the url changes ?
and what does html5mode does to the browser ? In the newer frameworks like react and angular(2 or greater) , you don't even have to enable html5mode(except in angular 2 where you have to tell what kind of url you want) .
What is this sorcery ?
This uses the History API.
It is designed so that developers can:
Tell the browser things like "I have used JavaScript to change the contents of the page. It is now the same as the page you would get if you asked for /other/page"
Intercept clicks on Back and Forward so that they can use JS to change the contents of the page to the be the same as the URLs that would be navigated to if the click on Back/Forward wasn't intercepted.
This updates the browser history and the URL in the address bar without triggering a normal navigation to a fresh page. The idea is that you can provide a smoother, faster transition between pages while still having real URLs that work well if you link to them or come back to them later.
That way:
If the JavaScript fails for any reason, the real URLs can still deliver the page
If a search engine indexes the URL, it gets the real data from it
If a visitor lands on a URL that isn't the homepage, they get the content they asked for immediately without having to wait for JavaScript to run, making additional Ajax requests, and assemble all the pieces client side.
It was designed in response to people using hangbangs instead of real URLs.
Now in order to remove the hash you have to set html5mode true and you have to tell the server to return the index page for every request other than your apis
This is terrible advice from Angular.
It abandons all of the good stuff that the history API can provide in order to have all the drawbacks of hashbangs, but with nicer looking URLs.
The problem with doing it properly is that it requires duplicating the logic on the server and the client, which is a lot of work. Isomorphic JavaScript is an approach to reduce this workload.
and what does html5mode does to the browser ?
Nothing. The html5mode variable is read by Angular. The browser doesn't care about it directly. It tells Angular to use the History API instead of hangbang URLs.
In the newer frameworks like react and angular(2 or greater) , you don't even have to enable html5mode(except in angular 2 where you have to tell what kind of url you want) .
They just use the History API by default.

Is there a way, using javascript, to check a website's server/database for changes that were sent and then implement a reload?

So what the title says. Can I check a website's server/database (Or whatever it is called, sorry I'm new to coding) for changes made to the website so I can implement a reload and then implement my code.
In your site's JavaScript you can make small requests back to your web server without reloading the whole page, then take some action; e.g. change the content on part of your page, or maybe navigate somewhere else. You can choose a specific URL to request data from. The common way to structure things is using REST and JSON.
The regular part of your site would live at www.example.com/myaccount, etc., and your REST API would live at www.example.com/api/account/posts?dateafter=blah. You can use client-side JS libraries like JQuery to send requests up to your REST API, deserialize the resulting JSON into JS objects, then take action.
On the server side, various frameworks will help you build APIs, with appropriate routing. It depends what kind of hosting, language expertise, etc. that you have.

Facebook Login - JavaScript or PHP SDK

I am at the stage where I am thinking of integrating a social login method into my site. Of course my first one will be the facebook login before moving onwards.
Basically my question is : Which language is best for this type of OAuth connection, and which is going to let me do everything I want?
This will encompass all OAuth connections in general eventually, but specifically Facebook for now.
From what I have read of the documentation, the JavaScript SDK allows you to login, and connect to the open graph API - which in turn will allow me to post / upload etc etc. This is also available in PHP.
From experience which is the more durable route to go?
PHP or JAVASCRIPT
The best and recommend way to authorize users is the JavaScript SDK (FB.login). No redirect needed (better usability), very easy to handle, no PHP needed (the new PHP SDK needs PHP 5.4+). Use PHP only for stuff that involves usage of the App Secret or Extended Access Tokens. And for cron jobs, obviously. You can even just forget about the PHP SDK and use your own CURL calls.
Btw, security is no problem, you should just activate "appsecret_proof" in the App Settings.
More information about appsecret_proof:
https://developers.facebook.com/docs/graph-api/securing-requests
http://www.devils-heaven.com/facebook-php-sdk-4-0-tutorial/
One more reason (and one of the most important ones) is the possibility to refresh Access Tokens (=User Sessions) easily without page refresh by using FB.getLoginStatus.
And another reason is that you need to upgrade to new PHP SDK versions on your own. The JavaScript SDK does not need any upgrades, in the lase few years you only had to change one or two parameters in some cases, the SDK gets downloaded from the Facebook servers.
Also, if you add Social Plugins, you need the JavaScript SDK anyway.
TL;DR PHP/both
I'd really recommend PHP. You'll want to store the login in database. If you do it via JS, you'll need to make an Ajax call to the server, which is not really that secure.
Having said that, they are targeted for different uses. JS is for frontend more, while PHP is for backend (db storage, checks, actual site login, etc). Using JS will let you generate the buttons on the fly, while using PHP you'll need to do some more coding.
Somehting else, the php library will get updated from time to time and you'll need to keep up after testing. JS also, but it's easier, since the code usually works.
If you only want one, use PHP. You can control what the code does and JS will not break your site since it's written by you. However, I'd recommend using both since you will probably want more than just simple login
Edit:
As facebook states, use PHP SDK: Usually this means you're developing with PHP for a Facebook Canvas app, building your own website, or adding server-side functionality to an app that already uses the Facebook SDK for JavaScript.
https://developers.facebook.com/docs/reference/php/4.0.0
The best route would be to use both, together. Some users might have javascript disabled or you might do something within your javascript code that will not work on some browsers. So as a fallback method you can use php api.
Going with only php would be solid and will work regardless of what the users client is, but you can make the user experience better with javascript.
Still, in most cases you'll end up having to use both.
I have just spent the afternoon playing with the JavaScript SDK for facebook and I have to admit I think this is going to be the best option for what I need.
If anyone else is reading this, it may not be perfect for you - but with the way my application has been built I think it is a perfect fit. Here is why :
My standard login system uses JavaScript to grab my form data, then validate, which then passes the validated data via AJAX to a PHP validation script. Which in turn returns a JSON response to the original AJAX call. If my call comes back with "ok" : true then we are good to go basically.
The way the facebook JavaScript SDK works is almost a perfect little jigsaw puzzle to bolt onto the system I am using. All I require is a little bit of profile data, to then keep a record of this user on my system. THIS is provided by facebook, then validated by myself.
However, other social network logins may not be as nice and simple to use as the facebook API, so I could end up changing my mind on the overall system. For now just using facebook, I think the JavaScript SDK is absolutely spot on, as it just gets the information for you to run through your own validation on site. As I said this is a perfect fit for my system however it may not be for yours.

Stateless (pushState?) back button on ajax forum

I need a stateless way to implement the back button feature in an ajax forum such that if a user is on page 2 of the topics ajax page, and then clicks on the message - when the user then hits the back button they can go back to the point of the message on the topics ajax page. - your help would be much appreciated.
::Please remember I want a stateless way of doing this, such that it's done client side::
The only option you have is to implement a client-side routing mechanism which you can either achieve by changing the # in your url whenever you change state. For instance your topics page has a url like yourforum.html#topics and whenever a user clicks on a message, you redirect (client-side) to yourforum.html#message/3.
Your JavaScript code should listen to those hash changes and react accordingly by loading topics/messages.
There 2 ways of client-side routing:
changing the hash like in the example I made
HTML5 push-state
Many modern JavaScript frameworks like Backbone, JavaScriptMVC etc... support routing. So you might take a look at those. TodoMVC might be a good starting point. Otherwise try to google for some jQuery plugins which give you this kind of functionality.

Categories