简体   繁体   English

Nodejs Express 4路由Questin

[英]Nodejs Express 4 Routing Questin

I am trying to prepend a NodeJS request through express to include /api/v1. 我试图通过表达包含/ api / v1来添加NodeJS请求。 If I make an addition like to to my server.js file: 如果我对我的server.js文件做了一个补充:

app.all('/Employees', require('./routes/Employees'));

I am able to go forward to localhost/Employees and get the proper response (it comes back from the javascript I have written in ./routes/Employees) 我能够前往localhost / Employees并获得正确的响应(它来自我在./routes/Employees中编写的javascript)

If I add /api/v1/ to the beginning of the app.all call, like so: 如果我将/ api / v1 /添加到app.all调用的开头,如下所示:

app.all('/api/*', requireAuthentication);

I am not able to go forward to localhost/api/v1/Employees. 我无法前往localhost / api / v1 / Employees。 The express manual even has an explicit note about this: 快递手册甚至有一个明确的说明:

Another example is white-listed "global" functionality. 另一个例子是白名单的“全局”功能。 The example is much like before, however it only restricts paths that start with "/api": 该示例与之前非常相似,但它仅限制以“/ api”开头的路径:

http://expressjs.com/api.html#app.all http://expressjs.com/api.html#app.all

Any help would be greatly appreciated. 任何帮助将不胜感激。

Your app gets confused whenever request is received at /api/* -- it doesn't know where to go and what to do now. 无论何时收到/ api / *的请求,您的应用都会感到困惑 - 它不知道去哪里以及现在该做什么。

If you want to prefix /api/v1 for your requests, you can do it with couple of ways - Choose what best suits your in your case: 如果你想为你的请求添加/ api / v1前缀,你可以通过几种方式来做 - 在你的情况下选择最适合你的方法:

Mountpath way - Mountpath方式 -

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

api.all('/employees', function(req, res){
    console.log("url :: " + api.mountpath);
    res.send('hit at employess');
});

//you can do this here fo v(n)
app.use('/api/v1', api);

app.listen(3000);

other way - 另一种方式 -

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

app.all('/employees', function(req, res){
    res.send('/employe');
});
app.use('/api/v1', function(req, res, next){
    res.redirect(req.path);
});

app.listen(3000);

Happy Helping! 快乐帮助!

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

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