I need to use expressjs like routes on client side to be possible invoke callback function upon specific route like the following:
app.get('/dogs', function(req, res, next) {
// do stuff
});
Is there something like for client side?
I was looking for the same thing the other day, and I stumbled upon Page.js.
As the author describes it, it's a
Micro client-side router inspired by the Express router (~1200 bytes)
Plus, the original author is TJ Holowaychuk, the guy behind Express. So I guess Page.js and Express.js should have a few similarities :)
However, TJ posted on his blog about his departure from the Node.js world, so I don't know if he intends to maintain it.
Hope this helps.
Have you tried clint-side MVC frameworks like Ember, Angular, Bankbone(http://backbonejs.org/) etc?
Related
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.
I am looking at some code from someone else for learning purposes. The way they're mounting routes is vague to me.
app.use('/dist', express.static(path.join(CURRENT_WORKING_DIR, 'dist')))
// mount routes
app.use('/', userRoutes)
app.use('/', authRoutes)
app.use('/', postRoutes)
The confusing part for me is how they're using '/' and using app.use. I'm used to doing it with app.get() and on top of that you specify the route instead of putting '/' everywhere. How does this work? Is this better practice?
The repo I'm looking at is https://github.com/shamahoque/mern-social/tree/master/server
Writing routes directly can be confusing and difficult to manage if there are large number of routes. So according to MVC pattern, the application is divided into modules/logical blocks based on functionalities they perform. For example, a simple hospital management system can have authentication, billing, payroll , medical-stock , patients etc modules (imaginary). If you are building application using MVC pattern, the common practice is to write controller for each of the module. Express provides something called middleware also called as Router to attach these controllers to respective API routes (Imagine it as a sort of map that connects each route to respective controller).
Once you define routes for each of these modules through middleware, you use those routes with your application. These routes handle requests and send parameters to controller to process.
You can learn how to use Middleware and Routers here : https://www.tutorialspoint.com/expressjs/expressjs_routing.htm
Regarding quality of code, dividing the code into modules and using routers to connect them is less tedious for others to understand. It also provides a good view of the application and it becomes easier to add new modules / functionality.
You can read more about building production-ready express app here :
https://www.freecodecamp.org/news/how-to-write-a-production-ready-node-and-express-app-f214f0b17d8c/
Sorry for a nooby question. I'd ask it anyway!
I am playing around with AdonisJs. I understand it is a MVC framework. But I want to write REST APIs using the said framework. I could not find much help on the internet.
I have two questions:
Does the framework support writing REST APIs?
If yes to 1. then what could be the best starting point?
1. I've created 3 API projects with AdonisJS and think it's ideal for quick setup. It has many functions already included from start, supports database migrations and is pretty well documented in general.
You can create routes easily with JSON responses:
http://adonisjs.com/docs/3.2/response
Route.get('/', function * (request, response) {
const users = yield User.all()
response.json(users)
})
Or add them to a controller, and even fairly easily add route authentication with token protection (all documented):
Route.post('my_api/v1/authenticate', 'ApiController.authenticate')
Route.group('api', function () {
Route.get('users', 'ApiController.getUsers')
}).prefix('my_api/v1').middleware('auth:api')
2. Take a look at the official tutorial, you can probably finish it in about half an hour. http://adonisjs.com/docs/3.2/overview#_simplest_example
Start with defining some routes and try out echoing simple variables with JSON and just in regular views.
Move the test logic to Controllers
Read a bit more about the database migrations and add some simple models.
Don't forget the Commands and Factory, as you can easily define test data commands there. This will save you a lot of time in the long run.
Just keep in mind that you need to have a server with Node.JS installed to run the system on production (personally I'm keeping it running using a tool like Node Forever JS.
In order to create just a RESTful api you can use
npm i -g #adonisjs/cli
# Create a new Adonis app
adonis new project-name --api-only
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?
I'm starting to get my head around node.js, and I'm trying to figure out how I would do normal MVC stuff. For example, here's a Django view that pulls two sets of records from the database, and sends them to be rendered in a template.
def view(request):
things1 = ThingsOne.objects.all()
things2 = ThingsTwo.objects.all()
render_to_response('template.html, {'things1': things1, 'things2': things2})
What might a similar node.js function look like?
http://boldr.net/mvc-stack-node-js-ejsgi-scylla-mustache is a great little article with a full github example of a MVC pattern using dirfferent Node modules. It also lists alternate modules currently available. It answered this question for me better than http://howtonode.org/ which has some good tuts but I couldn't find anything on MVC there.
The easiest way to do this is with expressjs, which is an MVC framework for Node. Node is just what it says, evented I/O for the web.
The example on the http://expressjs.com should help with the basics but to answer your question directly.
var express = require('express');
var app = express.createServer();
app.get('/whatever', function(req, res) {
Things1.objects.getAll(function(things1) {
Things2.objects.getAll(function(things2) {
var options = { locals: { things1: things1, things2: things2 }};
res.render('thingstemplate.ejs', options); // or thingstemplate.jade or whatever
});
});
});
app.listen('80', ''); // port and optional hostname to bind
TowerJS is a popular MVC framework based on
MongoDB (database)
Redis (background jobs)
CoffeeScript
Stylus
Jasmine (tests)
jQuery
Site http://towerjs.org/
Source https://github.com/viatropos/tower
RailwayJS is a MVC framework, written in JavaScript based on ExpressJS and runs over nodeJS platform. It is inspired by Ruby on Rails framework. You can read about MVC architecture of RailwayJS here: http://jsmantras.com/blog/RailwayJS-Routing