0

所以在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中实现这一点?

谢谢

4

1 回答 1

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

于 2018-10-30T09:35:17.703 回答