How to create multiple html pages using one main route? - javascript

I'm trying to create a website that has multiple community feeds like one for bowling and another for poker like so: localhost:8088/communities/bowling & localhost:8088/communities/poker.
I use actix as my webserver operating under the Rust programming language.
Is there a way where all addresses operating under localhost:8088/communities encounter the same web files so that I can just have one main route?
Then store the additional header like /bowling or /poker so that I can commit to separate requests to the server for the relevant post feeds? Maybe I can save the additional header information in a javascript variable when the web page is called? -Like when I go to /poker, a variable named communityType gets set to poker. How would I do something like that?
Because there's no way anyone is making HTML pages for each of ~100s different communities.
Thanks for the help in advance!

I'm not very familiar with this crate, but based on the docs it looks like you can use #[get("/route/this/function/will/support")] to define how a route is handled. Assuming that I wrote it correctly, this should respond with small message telling you which community route you are on when using.
use actix_web::{get, web, App, HttpServer, Responder};
#[get("/communities/{name}")]
async fn communities_route(web::Path(name): web::Path<String>) -> impl Responder {
format!("This is the page for the {:} community!", name)
}
You could also expand it to have routes for say #[get("/communities/{name}/forums")] or #[get("/communities/{name}/{file}")] to handle common routes all communities have on a per community basis.
Edit:
It sounds like you also need to include .service(communities_route) in your main function when initializing the App to use #[get(x)]. You also have better control over how the route is handled if you configure the services directly.
Here is one snippet from their hello world example. It looks like it prints the request on the server so long as you visit any route other than "/index.html".
async fn index(req: HttpRequest) -> &'static str {
println!("REQ: {:?}", req);
"Hello world!"
}
App::new()
.service(web::resource("/index.html").to(|| async { "Hello world!" }))
.service(web::resource("/").to(index))
I recommend looking through their examples on github. It looks like they have a bunch of concise examples for many different use cases.

Related

Distributable/Distributed Web App with VueJS

I need to build a distributable app using VueJS. I'll describe the scene, so that it can be understood better.
Immagine the following:
Four companies have the same products database
Each of them has it's own politics, prices, custom colors, parameters, all of which are also stored in that database
These 4 companies want to integrate into their relative websites a page which shows their own catalogue (with their custom prices and politics and whatever), as well as, when you click on some of the products, the related information about that product
The question is: how can I make such an app using VueJS? Write it once and distribute it to these 4 different company websites?
And I've started to answer to my question doing the following:
I created an API which can be accessed by API Keys
Assigned to each company its very own API Key, so that requests coming with that API Key are associated with the given company
I created an app using VueCLI (which uses vue-router, for the pages/views, and axios for the API calls as well), wrote all my logic and components and styles and whatever else...and for development purposes I tried to use one of the 4 API keys (hard coding it into the axios.defaults.headers) to see if it all works...and it does!
Now, here comes the problem: I need to build/export the app in such a way that I can do something like this:
In www.company1.com/catalogue
Call catalogue.js and pass it the company1 API key
In www.company2.com/catalogue
Call catalogue.js and pass it the company2 API key
In www.company3.com/catalogue
Call catalogue.js and pass it the company3 API key
... I'll omit the company4 cause i'm sure you already got me.
Obviously I could export 4 different versions with the hard coded 4 different API's...but seems like a pretty stupid idea to me! Also, it exposes my client a lot cause, well, everybody could link to some of the companies' catalogue.js and, without configuration or whatever, visualise on it's own website my clients products..(which is obviously a problem).
I would like to have:
ONLY ONE catalogue.js file with some exposed parameters, as, for example: the API Key needed to identify the company.
In this way, everybody could still use that catalogue.js file, but with wrong credentials, it wouldn't produce a thing (i.e. will get an API error of unrecognized API key).
How on earth am I supposed to do this?
I'm banging my head on the wall from 2 weeks.
I've tried to export the app as Library, get errors like: Unknown custom element: <router-link> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
I tried to export the app as Web Component...got same error and others as well.
Please help me understand where I go wrong, and how should I approach the problem.
Look into Vue Environment Variables https://cli.vuejs.org/guide/mode-and-env.html
Or you can make independent settings.json file and load it through the axios

Have can I call the property(function) of the specified namespace with javascript cross different page?Asp.net Ajax or node.js is good solution?

In the admin web application site, Any way to make me use the same namespace javascript object in different page?for example, the first page is login page,if I create the javascript object, like below:
var App = {
username:"Tom",
password:"1234",
initLoginUI:function(){
......
},
initPageUI:function(){
......
}
}
After I login, I direct to index.html page, I want to call App.initPageUI() in index.html, is it impossible? How should I do that, could javascript expert give me some suggestion? Many Thanks!
Update:
I find one way is very close what I mean:
http://dotnetslackers.com/Community/blogs/bmains/archive/2009/05/30/ajax-and-type-registernamespace-how-it-works.aspx
It is Asp.Net Ajax, but if I don't know Asp.net, I only want to use javascript, maybe..... node.js??? But how to use node.js in my case?I want to some example.....I don't know too much about node.js...but I want to learn!!Or any popular(fancy) framework I can use?
Please give me any good suggestion, Many Thanks:)

REST API Node.js, organization

I m actually developping a REST API using Node.js and Express 4.0 and I wanted to clarify something.
The service is actually working, but in a single javascript file, and I m looking for a good way to cut it into multiples parts.
I was thinking about MVC, but with the actual route system, what is the controller ? Is it the declaration function of the route ?
How can I separate the different route into multiple files ? (like user_routes, billing_routes) etc... I know how to export module etc... but having app = express() in multiple file seems to not work (different instanciation)
And where to start to the listen the part ?
These are beginner questions, but please, but explicit :-)
Thanks for advance
You can check out some these examples:
mvc: https://github.com/visionmedia/express/tree/master/examples/mvc and
route-separation: https://github.com/visionmedia/express/tree/master/examples/route-separation
Also here there are 2 good posts on SO about the subject:
https://stackoverflow.com/a/13611448/2846161
ExpressJS How to structure an application?

Lazy Loading templates in Meteor

I use require.js to do lazy loading for a Javascript app. I would love to switch to a meteor stack but right now it looks like Meteor sends the whole app (all the templates) through on the initial load. Has anyone had success with require.js and meteor or any other implementation?
You're asking different questions, but certainly they are connected. The first is about loading additional javascript code into your meteor app. Of course you can use thing like requirejs. This should work fine supposing your lazy code is located in the public directory of your meteor project. However, my experience is that requirejs goes mad when the contents of public gets updated often, so for example in the development environment. Maybe it's a matter of customizing the library, but I would rather recommend using some lightweight homebrewed package. Look here, if you need some inspiration.
The second question is about lazy template definition. Each template consists of two parts. The first is its html code, written in handlebars syntax, the second is all the javascript code which you write to define how your template should behave (e.g. helpers, event handlers). The second part is easy, as long as we assume that we already know how to load the lazy code (see the above paragraph) and the template, lets call it myLazyTemplate, is already defined, so basically speaking Template.myLazyTemplate is not undefined. So how to achieve the latter?
To dynamically define a new template you'll need to call
Template.__define__(name, raw_func)
on the client. So the last question is "what is raw_func?". This is a compiled version of your html code which is normally created automatically on the server and then sent down the wire to the client when the app gets loaded (look here to see how it's done in meteor). But we want to do it dynamically, right?
So the idea is to compile the template code manually with a help of the Handlebars.to_json_ast routine. You can feed it with your template html code, and the output is some javascript array that can be sent to the client anytime by the method we've already talked about. The last thing you need to do is to call Handlebars.json_ast_to_func on the client, using the data sent from the server as the only argument. The output produced by Handlebars.json_ast_to_func is the raw_func you can use to produce myLazyTemplate template.
I'm aware that this is only a rough idea, not the whole solution to your problem. I hope this will help you to figure out the final solution on your own.

Ajax Design/Refactoring help when rendering new content - like list items and divs

I consistently come across this code smell where I am duplicating markup, and I'm not really sure how to fix it. Here's a typical use case scenario:
Let's say we'd like to post comments to some kind of article. Underneath the article, we see a bunch of comments. These are added with the original page request and are generated by the templating engine (Freemarker in my case, but it can be PHP or whatever).
Now, whenever a user adds a comment, we want to create a new li element and inject it in the current page's list of comments. Let's say this li contains a bunch of stuff like:
The user's avatar
Their name
A link to click to their profile or send them a private message
The text they wrote
The date they wrote the comment
Some "edit" and "delete" links/buttons if the currently logged in user has permission to do these actions.
Now, all of these things were already written in our template that originally generated the page... so now we have to duplicate it inside of Javascript!
Sure, we can use another templating language - like Jquery's Template plugin - to ease the pain generating and appending this new li block... but we still end up with duplicate html markup that is slightly different because we can't use macros or other conveniences provided to us by the templating language.
So how do we refactor out the duplication? Is it even possible, or do we just put up with it? What are the best practices being used to solve this problem?
This is a common problem and becomes more obvious as the UI complexity increases, and changes have to be done on both the server and client templates. This problem is fixable by using a the same template markup on both the client and server sides. The template processors must be written in both JavaScript and the server side language.
Two other solutions that are cleaner than the above approach, but both have their own problems:
Do everything client side
Do everything server side
If all markup generation is done on the client side, then the server acts more or less like a web service which only sends back data in whatever formats suits the application. JSON, and XML are really popular formats for most web services nowadays. The client always generates the necessary HTML and JS. If going with this approach, the boundary between the client and server must be well defined. Since the client has limited knowledge of what happens on the server, this means that proper error codes must be defined. State management will become harder since most/all server interaction will be happening asynchronously. An example of adding a comment with this approach may look like:
$('#add-comment').click(function() {
var comment = $('#comment-box').text();
$.ajax('http://example.com/add', {
success: function() {
addCommentRow(comment);
},
...
});
});
function addCommentRow(comment) {
var user = currentUser().name;
var html = "<li><b>{user}</b> says {comment}</li>";
html = html.replace("{user}", user).replace("{comment}", comment);
var item = $('<li>').html(html);
$('#comments').append(item);
}
The other approach is to do everything server side. Whenever a change happens, shoot a request to the server, and ask it for the updated view. With a fast backend, response times under a second, and proper indicators of network activity, the application should seem very responsive despite everything happening on the server. The above example would be simplified to:
$('#add-comment').click(function() {
$.ajax('http://example.com/add', {
success: function(response) {
$('#comments').html(response);
},
...
});
});
Although this seems a lot more cleaner on the client side than the previous approach, we have just moved the markup generation up to the server. However, if the application is not very AJAXy like Google Maps, then this approach may be easier to work with. Again, it's a matter of how complicated the application is, and perhaps maintaining state client side is a necessity for you, in which case you may want to go with the previous approach.

Categories