Javascript中的动态路由-Node.js

时间:2018-10-30 09:31:53

标签: javascript node.js class routing dynamic-routing

因此在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

当您获得类似www.domain / route / other-page的url时,通过一些正则表达式操作,就可以从字符串中获取字符串“ route”和“ other-page”,并将其转换为“ Route”和“ ohterPage”并将它们填充到$ controller和$ action变量中,您只需调用'$ controller-> $ action();'它将调用Route-> otherPage()来提供请求的模板

这是一个很不错的解决方案,因为当您说出40种不同的操作(例如提供模板和各种get和post请求)时,您可以仅添加5条路径来处理它,但是为此您需要动态引用对象和方法像上面一样。...有什么方法可以在javascript中实现?

谢谢

1 个答案:

答案 0 :(得分:0)

为此使用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')
})

引用:https://expressjs.com/en/guide/routing.html