保护特定的路由node.js
嗨,我使用Node.JS的基本身份validation来确保路线。 我很新的Node.JS,不明白下一个function在这种情况下做什么。 我想要做的是确保路线: /admin/
注意:这是一个用于学习的项目,所以login部分不会太严重,不会被实时使用。
authentication.js
var basicAuth = require('basic-auth'); exports.BasicAuthentication = function(request, response, next) { function unauthorized(response) { response.set('WWW-Authenticate', 'Basic realm=Authorization Required'); return response.send(401); }; var user = basicAuth(request); if (!user || !user.name || !user.pass) { return unauthorized(response); }; if (user.name === 'name' && user.pass === 'pass') { return next(); } else { return unauthorized(response); }; };
和app.js我导入模块authentication:
app.get('/admin/', authentication.BasicAuthentication, function(req, res){ console.log("hi u need to login"); });
所以我想要做的是如果authentication通过进一步路由用户。
提前致谢!
尝试:
app.get('/admin/', authentication.BasicAuthentication); app.get('/admin/', function(req, res) {});
这个function被称为中间件:
var basicAuth = require('basic-auth'); exports.BasicAuthentication = function(request, response, next) { function unauthorized(response) { response.set('WWW-Authenticate', 'Basic realm=Authorization Required'); return response.send(401); }; var user = basicAuth(request); if (!user || !user.name || !user.pass) { return unauthorized(response); }; if (user.name === 'name' && user.pass === 'pass') { return next(); } else { return unauthorized(response); }; };
中间件是一个可以为各种目的定义的function:
- 使用中间件
- 编写一个中间件
一个简单的方法是在执行另一个操作之前运行的一个函数,一个通用的目的是保护某些未经授权访问的路由。
你可以保护私人路由,然后调用authentication.BasicAuthentication函数(req,res){}
一些例子:
app.get('/user-profile/', authentication.BasicAuthentication, function(req, res){ //private info }); app.get('/foo/', function(req, res){ //public info });