Providing auth for static HTML/JS application with Sails.js - javascript

I have a client side application written in plain HTML/JS (Not with Angular.js or other front-end MVC framework). It contains multiple html file. each includes different js library.
I would like to provide basic user auth feature(using sails-generate-auth) to limit the access of this client-side application using Sails.js
But I'm having problem putting those html file into /views
Should I change all *.html in to *.ejs and edit /config/routes.js to route each file? How do I make use of the req.session.authenticated ? Please provide some direction. Thank you.

Your solution written in your question would work. Here is another option:
You can send the file straight from your controller or for universal usage you can create a custom response that will send the html file instead of attempting to render the ejs view. Call it sendHtml(), or modify the current ok.js to know and send your html files
http://sailsjs.org/#!/documentation/concepts/Custom-Responses
Use something like
res.sendfile('/views/' + rest.controller + '/' + res.action + '.html');

Related

How to pass data from nodejs to inside html script tags

I'm using expressjs as a server on 8000 port. I want to send a string value from expressjs file to html script tags and use this string value in script tags.
name variable is coming as a empty string now.
How can i console.log name variable's value?
static-pages-server.js:
app.get('/index', function(req, res) {
var name = "hello";
res.render(__dirname + "/static-pages/journey-analize-report/index.html", {name:name});
});
index.html:
<script type="text/javascript">
console.log(name);
</script>
Edit : I used ejs and now problem is how should i describe name attribute in script tags? Below code is giving syntax error.
<script type="text/javascript">
console.log(<%=name%>);
</script>
Express.js itself is a backend server. If you would like to have dynamic HTML files you need to use templates engines.
Please follow this document -> https://expressjs.com/en/guide/using-template-engines.html
Eventually, you will realize you will need a frontend framework to write your code faster with good quality. So also recommend you to take a look at some of the frameworks like React, Vue.js. If you need Single Page Applications you only use express.js to provide data not to render HTML. If you need Server-side rendering it is good to investigate Next.js, Nuxt.js.
You cant directly inject variables into a html file in nodejs . That is why you have templating engines in express. Check out ejs.
It would allow you to pass data directly from your routes into the page you are rendering.
Local variables sent to a view via the locals parameter using the res.render() method aren't directly accessible. Instead you need to refer to those using it's variable name wrapped inside double curly brackets. So if you want to use it inside a JavaScript function, you need declare a local variable and give it the content of your name local.
Simply modify your index.html like this:
<script type="text/javascript">
let name = "{{name}}";
console.log(name);
</script>
here is the answer How do I use HTML as the view engine in Express?
what you will need is a view engine package in your app. there are many view engines currently available.
then set that view engine in express app. Trigger the view render via a call from your route’s response like you have done above.
Then in your view render the html output using the view variables and if these variables are outputted into html you can use them in your in browser JavaScript. You can also call a service in your html sending the dynamic data as well.
check out esj or pug (ps pug is my personal favourite )

Client Side Routing - Any URL path

Is there a simple client side routing solution that will take any URL path value and pass it on to a variable? I would like it so https://URL/path saves the path value as a variable and loads index.html while preserving the URL.
I have looked at a couple of solutions (path.js & crossroads.js) but I don't quite understand how they work for binding any URL path and loading the default index.html file. I am not using any frameworks and would like to know if this is achievable with vanilla javascript.

How to load js files during web application startup through nashorn

I am working on an application which loads multiple js files on client side during first hit in browser. It takes quiet a bit of time to load the first page of our application which can be improved using server side rendering.
We are using java and spring in our backend application. So I am looking for a way to load all the js files on server side during application load(server startup) instead of client side. So I removed js file reference from the jsp and I am trying to load the js files using nashorn as below:
#Configuration
public class ConfigureScript {
#Bean
ScriptTemplateConfigurer configurer() {
ScriptTemplateConfigurer configurer = new ScriptTemplateConfigurer();
configurer.setEngineName("nashorn");
configurer.setScripts("/js/common/common.js", "/js/utils/utils.js");
configurer.setRenderFunction("render");
configurer.setSharedEngine(false);
return configurer;
}
}
But somehow this doesn't seems to work for me since application just keeps loading. Can you guys please suggest the problem with above code or some other way to achieve the server side loading of js files?
Also, if you can suggest is there a way to debug whether js files are loaded properly or not?
for debugging I use postman chrome plugin. When server side rendering takes place - hit to the basic url (e.g. "/" or any other supposed) returns the content rather than jsp template.
removing js files from jsp - not sure this is correct. js should handle anyway some users interactions in browser after the rendering on server side, except probably that would be fine if content returned from server is static.
in snipped above - two files are loaded. the way how nashorn works - it builds the entire hierarchy of js objects, required for rendering. Are those files enough? Implementation of "render" function should take the job to render.

Handling Dynamic Routes Without a Server

Is it possible to serve a dynamic html page without a backend server or without using a front-end framework like Angular?
Edit
To clarify, the index file is served from a backend. This question is about how to handling routing between the index and dynamic pages.
I have an application that consists of two files - index.html and dynamic.html. When the user clicks an option say "Option A", they are served dynamic.html and the url is updated to /option-a. Now, with a server this is no problem and assuming the user visits the app from the landing page, it isn't a problem either because a cookie can be set. However, suppose a user visits a page at my-domain/option-a. That route doesn't exist and there is no server to redirect so it will 404. They would have to visit dynamic.html.
I think this architecture demands that there's either a server to handle route redirects or a SPA framework.
Is there something I'm missing?
your SPA framework will be active only once your HTML page is loaded and to do that you need to redirect any URL that user tries for your domain to that HTML file. For this you obviously need a server (and since you are talking about my-domain/option-a I assume you have atleast a basic server). You can refer to this link to get an idea on how server can redirect a URL to specific html file: Nodejs - Redirect url.
Once HTML is loaded you can initialize your SPA framework and decide the template to be loaded based on the URL.
Note: without a server you will access URLs using file://somepath/index.html and anything other than this URL will result in 404 and no SPA framework can handle that.
I think the solution is to use a static site generator such as Jekyll or Middleman and allows you to convert information into static pages. That way you functionally are building a bunch of pages but they are all compiled ahead of time. You can add dynamic content that is loaded in from a yaml file and it will compile the content into separate html pages.
It is not possible, but there is a workaround using url parameters like this:
my-folder/index.html
my-folder/index.html?=about
my-folder/index.html?=about/sublevel
my-folder/index.html?=profile
my-folder/index.html?=./games
const urlParams = new URLSearchParams(location.search);
const route = urlParams.get('');
console.log(route);
// Should print "about" "about/sublevel" "profile" "./games"
Of course this approach is not as clean as using a server for routing, but it's the best you can get without a server.
BTW. I tried an alternative solution creating symlinks with all the target routes pointing to the same index.htmlfile. But it did not work because the browser (firefox) redirects by default when it finds a symlink, thus home is shown all the time.

asp.net MVC routing - javascript url 404 errors

While developing my app (asp.net mvc3) locally everything was fine using the VS dev app server. The app was located at localhost/. However, I'm attempting to deploy the application on a IIS 7.5 server in a /Management directory and having a lot of routing issues as a few calls in my app rely on the app being at the route.
I have some javascript code that calls my controller through an ajax call that looks like this:
url: "/en/Home/GetFormula/"
I would like it to go to: /Management/en/Home/GetFormula but instead it's going to the root of the site and looking for /en/Home/GetFormula and returning 404 errors.
Any ideas on how I can fix my javascript routing to default /Management/ as the root of the site?
Thanks
When the pseudo-URL passed to an HTTP request begins with a slash (e.g. "/path/to/resource"), the pseudo-URL is "completed" by treating it as if the given path were under the Web site's root directory (e.g. "http://my.site/path/to/directory").
Clearly, you were expecting the pseudo-URL to be processed as if the given path were under your Web application's root directory. Well, I have bad news for you: The HTTP protocol does not deal with such a thing as a "Web application".
The ASP.NET MVC Framework provides the Url.Content function, which takes pseudo-URLs beginning with a tilde character (e.g., "~/path/to/resource") and returns the result of replacing the tilde character with the Web application's root directory (e.g., "http://my.site/an/application/path/to/resource", assuming the Web application's root directory is "http:/my.site/an/application"). However, the ASP.NET MVC Framework is only available on the server side. If your JavaScript runs on the client side, it cannot call Url.Content.
But not all is lost. The ASP.NET MVC Framework allows you to dynamically generate JavaScript code on the server and run it on the client, the same way it allows you to dynamically generate HTML content and of course send it to the client. That way, you can expand the pseudo-URLs into actual URLs on the server side, and deploy the resulting JavaScript code to the client.
To avoid confusion about where you are currently try:
url: document.URL + "/Management/Home/GetFormula"
I solved this issue adding a html hidden field on my page where, on the server side, I put the correct url inferred with the Url.RouteUrl method like this:
<input id="MyHiddenFieldName" name="MyHiddenFieldName" type="hidden" value="#Url.RouteUrl(new { area = "MyArea", controller = "MyController", action = "MyAction" />
then, on your javascript code you could do this:
url: $("#MyHiddenFieldName).val()

Categories

Resources