0

我是一个 node.js 新手,发现自己对以下简单要求感到有些困惑:

我想使用具有以下结构的 url:

/报告/34eabc

...我希望它以“34aebc”作为参数路由到 /public/report.html,我可以通过客户端 Javascript(Bootstrap.js 框架)访问该参数。

我的服务器是这样设置的:

//Create server
var app = express();

// Configure server
app.configure( function() {
    //parses request body and populates request.body
    app.use( express.bodyParser() );
    //checks request.body for HTTP method overrides
    app.use( express.methodOverride() );
    //perform route lookup based on url and HTTP method
    app.use( app.router );
    //Where to serve static content
    app.use( express.static( path.join( application_root, 'public') ) );
    //Show all errors in development
    app.use( express.errorHandler({ dumpExceptions: true, showStack: true }));
});


//Start server
var port = 4711;
var server = require('http').createServer(app), io =require('socket.io').listen(server);
server.listen( port, function() {

    console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});

// Routes
app.get( '/api', function( request, response ) {

    response.send( 'API is running' );

});

我希望在中间件框架方面尽可能地轻量级,但我觉得我可能错过了我应该在这里使用的范式。

4

1 回答 1

1

只需使用命名参数:

app.get( '/report/:id', function(req,res){
    var id = req.params.id;
    // id gets the value '34eabc' (or whatever is passed in in the URL)
    // do your stuff....
});
于 2013-07-02T23:48:32.507 回答