简体   繁体   English

Javascript中的动态路由-Node.js

[英]Dynamic Routing In Javascript - Node.js

So in php you can do dynamic routing like 因此,在php中,您可以像

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();' 当您获得诸如www.domain / route / other-page之类的URL时,通过进行一些正则表达式操作,就可以从字符串中获取字符串“ route”和“ other-page”,并将其转换为“ Route”和“ ohterPage”并填充它们放入$ controller和$ action变量中,您只需调用'$ controller-> $ action();' and it will call Route->otherPage() which will serve up the requested template 它将调用Route-> otherPage()来提供请求的模板

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? 这是一个很不错的解决方案,因为当您说出40种不同的操作(例如提供模板和各种get和post请求)时,您仅需添加5条路由即可处理该问题,但是您需要像上面那样动态引用该对象和方法。 ...有没有办法在javascript中实现这一目标?

Thanks 谢谢

Use Express Js for this: 为此使用Express Js:

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 请参阅: https//expressjs.com/en/guide/routing.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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