简体   繁体   中英

Dynamic Routing In Javascript - Node.js

So in php you can do dynamic routing like

class Route
{
  public function homePage ()
  {
    echo 'You are on the home page'
  }

  public function otherPage ()
  {
    echo 'You are on some other page'
  }
}

class Route2
{
  public function homePage ()
  {
    echo 'You are on the home page'
  }

  public function otherPage ()
  {
    echo 'You are on some other page'
  }
}
// when you get the url like www.domain/route/other-page, with some regex operation you get out as string 'route' and 'other-page' from the route transform it to 'Route' and 'ohterPage' and fill them into the $controller and action variables and you just call:
$controller->$action();
// and it will call Route->otherPage() which will serve up the requested template

when you get the url like www.domain/route/other-page, with some regex operation you get out as string 'route' and 'other-page' from the route transform it to 'Route' and 'ohterPage' and fill them into the $controller and $action variables and you just call '$controller->$action();' and it will call Route->otherPage() which will serve up the requested template

it is nifty solution because then when you have lets say 40 different actions like serving up templates and various get and post request then you can handle it with adding just 5 routes but for this you need to reference the object and the method dynamically like above.... is there any way to achieve this in javascript?

Thanks

Use Express Js for this:

var express = require('express')
var app = express()

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
  res.send('hello world')
})

Refer: https://expressjs.com/en/guide/routing.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM