简体   繁体   English

如何在路由器中正确使用Express中间件功能?

[英]How to use Express middleware functions correctly in router?

In this example below, you can see that the csrfProtection and parseForm functions are passed as parameters/callbacks in the GET and POST requests... 在下面的示例中,您可以看到csrfProtectionparseForm函数在GET和POST请求中作为参数/回调传递。

var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')

// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })

// create express app
var app = express()

// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())

app.get('/form', csrfProtection, function(req, res) { // HERE 
  // pass the csrfToken to the view
  res.render('send', { csrfToken: req.csrfToken() })
})

app.post('/process', parseForm, csrfProtection, function(req, res) { // AND HERE
  res.send('data is being processed')
})

However, if you are using a router, like I am, how can use these same functions? 但是,如果您像我一样使用路由器,那么如何使用这些相同的功能? I am aware that by "using" them in app.js, they are made available on the req object but in the example given above, they are required as the 2nd and 2nd & 3rd arguments of the GET and POST routes, but req isn't made available until you're inside the final callback?! 我知道通过在app.js中“使用”它们,它们可以在req对象上使用,但是在上面给出的示例中,它们是GET和POST路由的第二,第二和第三参数所必需的,但是req不是直到您进入最终回调之前,都无法使用?!

So I know you can't do the below (just as an example)... so how should you use them? 因此,我知道您不能执行以下操作(仅作为示例)...那么您应该如何使用它们? Would I have to re-declare them in every routes file? 我需要在每个路由文件中重新声明它们吗?

Separate routes file: routes/someroute.js ... 单独的路由文件:routes / someroute.js ...

router
    .post('/', req.body, req.csrfProtection, (req, res) => {

    })

... ...

Thanks in advance :) 提前致谢 :)

Reference: https://www.npmjs.com/package/csurf 参考: https : //www.npmjs.com/package/csurf

UPDATE UPDATE

Following comments below, I have made the following changes to my app.js file. 根据以下评论,我对app.js文件进行了以下更改。

app.js app.js

... ...

global.bodyParser = require('body-parser').urlencoded({extended: false});
app.use(global.bodyParser);

global.csrfProtection = csrf({ cookie: false });

... ...

routes/myroute.js 路线/ myroute.js

router
    .post('/', global.bodyParser, global.csrfProtection, (req, res) => {})

However, when I restart the server I am seeing this error, which suggests that that the global function is not defined... what am I missing here? 但是,当我重新启动服务器时,我看到此错误,这表明未定义全局函数...我在这里错过了什么? :-/ : - /

Error: Route.post() requires a callback function but got a [object Undefined]

I think you ask about sharing middlewares across all API/routes files 我想您问有关在所有API /路由文件之间共享中间件的问题

You can do it like this : 您可以这样做:

First in your main file lets call it server.js we use you're code 首先在主文件中将其命名为server.js我们使用的是您的代码

var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')

// create express app
var app = express()

// setup route middlewares
app.use(bodyParser.urlencoded({ extended: false }))

// parse cookies
app.use(cookieParser())
//enable your JS API/route script.
const awesomeAPI = require('./awesomeApi.js');
app.use('/awesome', awesomeAPI );
app.listen(3000);

Now you have file let's calle it awesomeApi.js 现在您有了文件,将其awesomeApi.js

const express = require('express');
const awesomeApi = express.Router();
awesomeApi.route('/')
   .post(req,res => {
  //req.body present here. And body parser middle ware works.
})
module.exports = awesomeApi;

Hope this helps. 希望这可以帮助。

Some links: 一些链接:

https://expressjs.com/en/guide/using-middleware.html https://expressjs.com/en/guide/using-middleware.html

https://expressjs.com/en/4x/api.html#express https://expressjs.com/en/4x/api.html#express

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

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