1

它可用于

app.get('/', function(req, res){
  res.send('hello world');
});

这是在接收到定义的端口上的请求时显示在浏览器中。

命令 app.get 还有哪些其他用途?

4

2 回答 2

4

app.get 有两个用途。

第一种是像您展示的那样将其用作路由,或者甚至在路由之外使用多个中间件,如下例所示:

var middleware = function(req, res, next) {
    //do something, then call the next() middleware.
    next();
}

app.get('/', middleware, function (req, res) {
   res.render('template');
});

但 app.get 也可以与 app.set 一起使用:

var appEnv = app.get('env'); //tells you the environment, development or production
var appPort = app.get('port'); //tells you the port the app runs on
console.log('app is running in ' + appEnv + ' environment and on port: ' + appPort);

app.set('any-string', 'any value'); //set custom app level value
var any_string = app.get('any-string'); //retrieve custom app level value
console.log('any_string = ' + any_string);

这就是我到目前为止发现的 app.get 的用途,

玩得开心

亚沙

于 2013-07-14T11:53:23.337 回答
3

在 express中app.getapp.post用于定义路由。它们都以相同的方式工作。他们接受两个参数

1) 定义路由路径的字符串

2) 单个或多个回调。

app.get('/', function(req, res){
res.send('hello world');
});

上面代码的作用是告诉 express,当在端点上发出请求时,/它会执行回调函数中的代码。您定义的函数只是发送一条 html 消息

但是,您可以向浏览器发送许多不同的响应。指南中列举了它们

于 2013-07-14T10:25:57.100 回答