express.js中app.use和app.get的区别 [英] Difference between app.use and app.get in express.js

查看:114
本文介绍了express.js中app.use和app.get的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很喜欢表达和node.js,我无法弄清楚app.use和app.get之间的区别。看来你可以使用他们两个来发送信息。例如:

  app.use('/',function(req,res,next){
res。 send('Hello');
next();
});

似乎与以下相同:

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


解决方案

app.use() 旨在绑定中间件到您的应用程序。 路径挂载前缀路径,并限制中间件仅适用于请求的任何路径 开始 。甚至可以用来嵌入另一个应用程序:

  // subapp.js 
var express = require('express );
var app = modules.exports = express();
// ...



  //服务器.js 
var express = require('express');
var app = express();

app.use('/ subapp',require('./ subapp'));

// ...

通过指定 / 作为挂载路径, app.use()将响应以$开头的任何路径c $ c> / ,这些都是它们,不管使用的是HTTP动词:




  • GET /

  • PUT / foo

  • POST / foo / bar

  • 等。


$ b $另一方面,b

app.get()是Express'应用程序路由,并且用于在请求时使用 GET HTTP动词来匹配和处理特定路由:




  • GET /



而且,您的 app.use()示例的等效路由实际上将是:

  app.all(/ ^ \ /.*/,function(req,res){
res.send('Hello');
});


I'm kind of new to express and node.js, and I can't figure out the difference between app.use and app.get. It seems like you can use both of them to send information. For example:

app.use('/',function(req, res,next) {
    res.send('Hello');
    next();
});

seems to be the same as this:

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

解决方案

app.use() is intended for binding middleware to your application. The path is a "mount" or "prefix" path and limits the middleware to only apply to any paths requested that begin with it. It can even be used to embed another application:

// subapp.js
var express = require('express');
var app = modules.exports = express();
// ...

// server.js
var express = require('express');
var app = express();

app.use('/subapp', require('./subapp'));

// ...

By specifying / as a "mount" path, app.use() will respond to any path that starts with /, which are all of them and regardless of HTTP verb used:

  • GET /
  • PUT /foo
  • POST /foo/bar
  • etc.

app.get(), on the other hand, is part of Express' application routing and is intended for matching and handling a specific route when requested with the GET HTTP verb:

  • GET /

And, the equivalent routing for your example of app.use() would actually be:

app.all(/^\/.*/, function (req, res) {
    res.send('Hello');
});

这篇关于express.js中app.use和app.get的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆