Node.js在Express 4中有条件地使用csurf [英] Node.js use csurf conditionally with express 4

查看:268
本文介绍了Node.js在Express 4中有条件地使用csurf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在我的Express应用程序中的仅几条路线上使用csurf。
就是这种方法:

I try to use csurf on just a few routes in my express app. that's the approach:

var express       = require('express');
var session       = require('express-session');
var csrf          = require('csurf');

// some more stuff

var csrfExclusion = ['/myApi','/unsecure'];

var app   = express();

var conditionalCSRF = function (req, res, next) {  
  if (csrfExclusion.indexOf(req.path) !== -1){
    next();
  }
  else{
    csrf();
  }
});

app.use(conditionalCSRF);

甚至尝试过:

var conditionalCSRF = function (req, res, next) {  
  if (csrfExclusion.indexOf(req.path) !== -1){
    next();
  }
  else{
    csrf(req, res, next);
    next();
  }
});

var conditionalCSRF = function (req, res, next) {  
  if (csrfExclusion.indexOf(req.path) !== -1){
    next();
  }
  else{
    csrf();
    next();
  }
});

但这给我一个错误:对象#没有方法'csrfToken'

But this gives me an error: Object # has no method 'csrfToken'

如何有条件地使用csurf。该文档仅提供在Express app中所有路径上使用它的信息,

How can I use csurf conditionally. The documentation only gives information to use it on all routes in the express app with

app.use(csrf());

但这不是我想要的,我想排除一些路线...

But that's not what I want, I want to exclude some route...

请稍等...马丁

更新:

UPDATE:

终于可以了。我做了以下事情:

finally it works. I did the following:

app.use(function(req, res, next){
  if (csrfExclusion.indexOf(req.path) !== -1) {
  next();
}
  else {
  csrf()(req, res, next);
});

这有条件地添加了csrf中间件。
但是我真的这么称呼它很奇怪:

This adds the csrf middleware conditionally. But I really think it's kind of strange to call it like this:

csrf()(req, res, next);

我什至没有得到语法...

I even do not get the syntax...

推荐答案

根据,您需要将其拆分为两台路由器,一台使用csurf,一台不使用。然后,您将中间件而不是应用程序应用到路由器。

According to this you need to split it up into two routers, one using csurf and one not. You'd then apply the middleware to the router instead of the app.

var routes = express.Router();
var csrfExcludedRoutes = express.Router();

routes.use(csrf());

routes.get('/', function(req, res) {
    //has req.csrfToken()
});

csrfExcludedRoutes.get('/myApi', function(req, res) {
    //doesn't have req.csrfToken()
});

这篇关于Node.js在Express 4中有条件地使用csurf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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