简体   繁体   English

NodeJS Express 根路径

[英]NodeJS Express Root Path

In NodeJS Express module, specifying path "/" will catch multiple HTTP requests like "/", "lib/main.js", "images/icon.gif", etc在 NodeJS Express 模块中,指定路径“/”将捕获多个 HTTP 请求,如“/”、“lib/main.js”、“images/icon.gif”等

 var app = require('express')
 app.use('/', authenticate);

In above example, if authenticate is defined as followed在上面的例子中,如果authenticate被定义如下

var authenticate = function(request, response, next) {
    console.log("=> path = " + request.path);
    next()
}

Then you would see然后你会看到

=> path = /
=> path = /lib/main.js
=> path = /images/icon.gif

Could anyone advise how to define path in Express "app.use" that only catch "/"?谁能建议如何在 Express “app.use” 中定义只捕获“/”的路径?

If you are trying to expose static files, people usually place those in a folder called public/ .如果您尝试公开静态文件,人们通常会将它们放在名为public/的文件夹中。 express has built-in middleware called static to handle all requests to this folder. express 有内置的称为static中间件来处理对这个文件夹的所有请求。

var express = require('express')
var app = express();

app.use(express.static('./public'));
app.use('/', authenticate);

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

Now if you place images/css/javascript files in public you can access them as if public/ is the root directory现在,如果您将 images/css/javascript 文件放在 public 中,您可以访问它们,就好像public/是根目录一样

<script src="http://localhost/lib/main.js"></script>

As far as I understand, what you need to do is if you have '/' & '/abc' you need to catch it separately.据我了解,您需要做的是,如果您有 '/' & '/abc' ,则需要单独捕获它。

This will do the trick:这将解决问题:

app.use('/abc', abc);
app.use('/', authenticate);

Means, register the /abc middleware first, then do the / middleware.意思是先注册/abc中间件,再注册/中间件。

There is an issue with this solution also.此解决方案也存在问题。 Here we declared /abc only.这里我们只声明了 /abc。 So when user calls an unregistered path, then it will hit here.所以当用户调用一个未注册的路径时,它会点击这里。 You can make use of originalUrl property in request object to determine its / only or there is something else.您可以使用请求对象中的 originalUrl 属性来确定它的/仅或还有其他内容。 Here is the documentation for this : http://expressjs.com/en/api.html#req.originalUrl这是此文档: http : //expressjs.com/en/api.html#req.originalUrl

if(req.originalUrl !== '/'){
   res.status(404).send('Sorry, we cannot find that!');
}
else{
  /*Do your stuff*/
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM