簡體   English   中英

Javascript中的動態路由-Node.js

[英]Dynamic Routing In Javascript - Node.js

因此,在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中實現這一目標?

謝謝

為此使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM