특정 경로를 제외한 모든 경로에 대해 Express의 특정 미들웨어 사용
일부 미들웨어 기능과 함께 node.js에서 Express 프레임 워크를 사용하고 있습니다.
var app = express.createServer(options);
app.use(User.checkUser);
내가 사용할 수있는 .use
특정 경로에이 미들웨어를 사용하는 추가 매개 변수와 기능 :
app.use('/userdata', User.checkUser);
특정 경로, 즉 루트 경로를 제외한 모든 경로에 미들웨어가 사용되도록 경로 변수를 사용할 수 있습니까?
나는 다음과 같은 것에 대해 생각하고 있습니다.
app.use('!/', User.checkUser);
따라서 User.checkUser
루트 경로를 제외하고 항상 호출됩니다.
홈페이지를 제외한 모든 경로에 checkUser 미들웨어를 추가합니다.
app.get('/', routes.index);
app.get('/account', checkUser, routes.account);
또는
app.all('*', checkUser);
function checkUser(req, res, next) {
if ( req.path == '/') return next();
//authenticate user
next();
}
인증되지 않은 경로의 배열에서 req.path를 검색하려면 밑줄을 사용하여이를 확장 할 수 있습니다.
function checkUser(req, res, next) {
var _ = require('underscore')
, nonSecurePaths = ['/', '/about', '/contact'];
if ( _.contains(nonSecurePaths, req.path) ) return next();
//authenticate user
next();
}
User.checkUser
미들웨어 로 직접 등록하는 대신 checkUserFilter
모든 URL에서 호출되지만 지정된 URL에서만 userFiled`에 실행을 전달 하는 새로운 도우미 함수를 등록 합니다. 예:
var checkUserFilter = function(req, res, next) {
if(req._parsedUrl.pathname === '/') {
next();
} else {
User.checkUser(req, res, next);
}
}
app.use(checkUserFilter);
이론적으로 정규 표현식 경로를 app.use
. 예를 들면 다음과 같습니다.
app.use(/^\/.+$/, checkUser);
express 3.0.0rc5에서 시도했지만 작동하지 않습니다.
새 티켓을 열어 기능으로 제안 할 수 있을까요?
각 경로마다 미들웨어를 설정할 수도 있습니다.
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
res.send('welcome, ' + req.body.username)
})
사용하다
app.use(/^(\/.+|(?!\/).*)$/, function(req, resp, next){...
이것은 /를 제외한 모든 URL을 전달합니다. 나를 위해 작동하지 않는 한.
일반적으로
/^(\/path.+|(?!\/path).*)$/
( 정규식에서 특정 단어를 부정하는 방법 참조 )
도움이 되었기를 바랍니다
express-unless 라는 라이브러리를 사용하십시오.
경로가 index.html이 아닌 경우 모든 요청에 대해 인증이 필요합니다.
app.use(requiresAuth.unless({
path: [
'/index.html',
{ url: '/', methods: ['GET', 'PUT'] }
]
}))
Path it could be a string, a regexp or an array of any of those. It also could be an array of object which is URL and methods key-pairs. If the request path or path and method match, the middleware will not run.
This library will surely help you.
'Development Tip' 카테고리의 다른 글
스레드 대 스레딩 (0) | 2020.12.11 |
---|---|
SQL : MySQL에서 기존 열을 기본 키로 설정 (0) | 2020.12.11 |
설치된 경우 응용 프로그램으로 리디렉션하고 그렇지 않으면 App Store로 리디렉션합니다. (0) | 2020.12.11 |
두 개의 지저분한 감시 작업을 동시에 실행하는 방법 (0) | 2020.12.11 |
maven에서 jacoco JVM 인수와 확실한 JVM 인수를 함께 사용할 수 없습니다. (0) | 2020.12.11 |