File based routing in NodeJS/ExpressJS - javascript

Is there a way to do the following in NodeJS (or ExpressJS)?
While I understand the flexibility routing offers, I pretty much dislike the way it has to be configured. (I am no expert in Express)
For example, the application structure is as shown below:
app
-- public // has all the static files.
-- dynamic // Root level file for something that contains all the dynamic pages
-- index.nsf // NSF == node server file (Just making up a sample extension here).
// NSF files have front matter and code like shown in section below
-- posts // A directory
-- view.nsf
-- edit.nsf
-- pages
-- thankyou.nsf
-- contactus.nsf
i.e when the user goes to the url "http://mydomain.com/pages/contactus", the content from that nsf file is rendered.
The NSF that I have in mind, will probably look like below - with just some YAML front matter
---
controller: contactUsController // A javascript file
layout: contact // Jade layout or HTML layouts
---
OR with some YAML front matter and layout as the content of the file.
---
controller: contactUsController
---
extends base
h1 This is the contact us page. Fill in the details below.
Even a one time configuration to setup a middleware like below would work:
app.use(app.**some_automatic_router**);
app.use(express.static(path.join(__dirname, 'public')));
Thank you.

Maybe you are looking for something like this :
https://npmjs.org/package/dynamic-routes

Related

Angular 2 routes - redirect to different app

I'm generating various versions of my app in alternate languages. I'm using AOT (ahead of time) compilations, so I end up with static deployable sites in a structure that looks like this:
dist -
index.html -- entry file for the default (English language) app
-fr
index.html -- entry file for French language version
-de
index.html -- entry file for German language version
I can currently switch between the main language websites using a dropdown where the user can select their preferred language, and I then load the main entry file for the required site using plain JavaScript like this:
const baseUrl = window.location.origin;
window.location.href = baseUrl + '/' + requestedLanguage + '/index.html'; // e.g. requestedLanguage = 'fr'
This works, as it seems that requesting the actual index.html file means Angular won't interpret the request href as an Angular route.
What I want to happen though is that when the user enters a URL that already contains the language version in the path, I want that language version to be served. I also want the URL path preserved so that the Angular routing loads the appropriate component for the requested URL.
For example:
user enters myDomain.com/fr/myPage
the app under the /fr/ subdirectory is loaded, and the Angular routing in that app loads the related component for MyPage
Currently if I enter a URL myDomain.com/fr/myPage, the Angular routing tries to interpret the desired subfolder fr as a route, which doesn't exist, so I get the following error:
Error: Cannot match any routes. URL Segment: 'fr/instruments'
How can I load the required app and the correct component? There must be a way of getting Angular to recognise that the fr in the URL refers to a different app. Maybe I'm missing a build configuration or something? Here's my script in package.json for building the French language version:
"build:fr": "ng build --aot --output-path=dist/fr --base-href /fr/ --i18nFile=src/locale/messages.fr.xlf --i18nFormat=xlf --locale=fr",
just use Components instead of different separate apps and use below example
>
{path:'',component:EnHomeComponent},
{path:'contact',component:EnContactComponent},
{path:'fr',component:LayoutComponent,
children:[
{path:'',component:FrHomeComponent},
{path:'contact',component:FrContactComponent}]}
then you can directly access the pages by URL
Use angular router concept for different paths of English, France and Danish.
Then use the path based on language.
I was able to load differing language versions of the app by configuring the pipeline for my .NET back end like this, so that the Angular static index page is loaded for each different language app (referred to as 'SPA' in the code). It works by checking if there is an 'index.html' page for the first subfolder in the request URL (e.g. '/fr/', '/de/'), and it loads that page if it exists:
Startup.cs
public class Startup
{
public void Configuration()
{
app.Use((context, next) =>
{
if (!context.Request.Path.HasValue)
return next();
IFileInfo fi;
string spaIndex = "index.html";
Uri uri = new Uri(context.Request.Uri.ToString());
var segs = uri.Segments;
var folder = segs.Length > 1 ? String.Format("/{0}", segs[1]) : "/";
if (!physicalFileSystem.TryGetFileInfo(context.Request.Path.Value, out fi)) {
// check if this is a request for a sub-application, e.g an alternative language version
// if so, load the app
if (physicalFileSystem.TryGetFileInfo(String.Format("{0}{1}", folder, spaIndex), out fi))
{
context.Request.Path = new PathString(String.Format("{0}{1}", folder, spaIndex));
}
}
return next();
});
}
}
The remainder of the URL (the part after the language subfolder) is then interpreted as a route inside the app that has been loaded (e.g. the French language app). This means that the correct component is loaded for the app (I'm not entirely sure how this part is working - maybe the remainder of the path falls through to a different part of the .NET request pipeline and is passed onto the Angular app?)

django retrieve data from database using ajax and update section

I am new to django, I was trying to design a webpage where a project section will have all the projects, on the same page there will be module section and under that module section there will be commits.
Now, What i want is when the user clicks on some project the module section should get updated with the modules under that project. I was able to do this much. (Here is everything you need to reference, you might need to hop into feed app there)
But the problem is, I used this in my ajax to update the module section.
$('#module_section').html(data);
Now the index.html doesn't know about the show details button in my module section (as it is retrieved from detail.html, my detail.html has the show details button which will show the commits done under that module) and when I press the show details button in my module section on the index.html page nothing happens, obviously.
I need a javascript/ajax that may be able to do a query like "Select * from module where project_id = 'some_id' " (Not sure about the syntax), and then update my module section accordingly so that when someone clicks on show details of module section he will be able to see the commits done under that module.
Any Suggestions would be highly appreciated, <3 in advance.
Create your html modules in separate templates. Lets say you have "index.html" and "details.html". Suppose both of these have a module that shows commits (call this the "commit module").
Create a separate html template that contains your module. call it "module_commit.html".
Then link a separate javascript file to it that contains all the javascript that contains it.
Now create a server side api for this module. This includes urls/views that return data and perform actions for your module.
Connect the modules javascript to call the api views and place the data in your module. ex:
Suppose you want the module to display a list of commits. You would create a view/url that returns the list of commits in JSON format. Then create a javascript function that, using ajax, calls this url endpoint and inserts the data into your html module (I would suggest using jquery for all of this because it is a lot easier to work with than vanilla javascript).
Now create an init function in your modules javascript file to make the needed calls to populate the module and set event triggers and events.
Now include your modules template in the main templates (index.html, details.html, etc...). Make sure the init function is called somewhere after the page loads.
Your code will have this layout:
api (models/views/urls)
A | (JS calls api to perform actions and retrieve data)
| V
javascript
| (Puts results from api into the modules html)
V
html
With this solution, you can just include ({% include 'module_commits' %}) the module in any template you want, call then init function in the javascript for that module, and it will work on any page. Just make sure your html ids don't conflict with others.

How do I add another page in an angular-cli project?

Based on the comments on another of my questions (gradle how to add files javascript fies to a directory in the war file) I'm trying to use angular-cli to help build and manage an angular project. However, I cannot seem to find any documentation on how to create a second webpage in the project, which to me seems like a very basic task. I tried creating a "component" with ng g component {component name}, but this didn't add anything to the build result.
I had missed the section of the angular docs on routing since I did not make the connection between the word "routing" and what I wanted to do. Routing as described here works perfectly when using Node as your server. However, other web servers such as Tomcat (which I am using for this project) will not since ng build only generates an index.html file. Node knows that it should re-route URLs under the angular base to that file, but Tomcat doesn't. A proxy server such as apache needs to be placed in front of the Tomcat server to redirect the urls to the base url for the application.
With that out of the way, here is the basics of routing:
create a component for each "page" (the component does not need to be responsible for the whole page displayed. see 2)
create a "shell" component that contains features that will be on all pages e.g. toolbar, side navigation.
add <router-outlet></router-outlet> to the point in the shell component component where components for sub-URLs will appear (note that they are inserted into the DOM after this tag, not within it.)
in the imports for your module, add RouterModule.forRoot(). This function takes an array of Route. Each route has a path and a component property. path is the url (relative to the base url) that will cause component to be inserted into the DOM. Note that path values should not begin with a slash.
add a tags with the routerLink property bound to the url of your new page. Note that here, there should be a leading slash.

where and how to serve files from , in node.js

I am new to node.js/express.js and I am reading some tutorials. I am confused because I am used to the simple apache logic, node.js/express.js logic confuses me. Please help me.
This tutorial uses the default express routes to add/get data from a db. But, at the begging , at the part named "PART 2 – OK, FINE, LET'S DO "HELLO, WORLD!" edits the ...\ROUTES\INDEX.JS file to add just a simple html page. Why is that?
Can I just use the public folder to serve my files and access the by using the same URL?
If I have like 50 files, I have to add 50 similar functions to my ...\ROUTES\INDEX.JS so I can serve them ? Even the simplest static files ?
Can I just put all my files in the public folder and then edit app.js and ...\ROUTES\INDEX.JS ?
Also I was reading the first chapter of the book Jump Start Node.js by Don Nguyen. It does not edit routes, just adds methods to the app.js and implements new modules (named db and user) for adding users to the db. This also adds a new get function to app.js for a simple form.html file.
Again, why can I use the public folder and then edit the app.js and create my own modules?
Again, If I have like 50 files, I have to add 50 similar functions to my app.js so I can serve them ? Even the simplest static files ?
Finally,
What is the difference between the two methods ? In which case I use them ?
Which one is the best practice ?
Thank you very much
To serve the folder named "public" as static files:
app.use(express.static(__dirname + '/public'));
The reason the tutorial did not put their 'simple' index page into public, is that their 'simple' page is not static. They pass in the data { title: 'Express' } to the dynamic page.
If the title 'Express' is always going to be static, then yes you can serve it from public. However for the sake of the tutorial, we assume they might dynamically change the title from 'Express' to something else.

Rails Routes and Static Pages

I'm working on a ruby-on-rails app that would write XML files for each section on a page. So instead of querying the database every time the user makes a request it would simply call the XML file that corresponds to that page and the javascript will parse the file. On the rails side there will be a content management system. When user is ready to commit all their content changes they will hit the publish file at which point the data which possibly was already saved in the database will now be written to an xml file.
The challenge is that I want all the xml files to live inside a folder in the main project directory called xml_display.
How do I configure the routes.rb to take a request like... myhost.com/display_xml/pagename.xml
and return the static page in rails_project_root/display_xml/pagename.xml
I've looked into High Voltage and it doesn't seem to be the solution I'm looking for.
I hope this sounds interesting to you.
You can just make a controller that redirects to your static files something like the following:
routes.rb
match '/display_xml/:id', :action => 'display'
display_xml_controller.rb
class DisplayXMLController
def display
redirect_to "http://#{host_domain}/static_xml_dir_in_public/#{params[:id]}.xml
end
end
You need to set host_domain to wherever you are running from. Most set up in a config.yml

Categories

Resources