简体   繁体   English

Express.js 在每个请求事件上?

[英]Express.js on every request event?

I was wonder if something like expained below even exist?我想知道是否存在像下面这样解释的东西?
Is it possible to make "middle execute" condition using express.js ?是否可以使用express.js制作“中间执行”条件?
I know it is difficult to explain, but look at the code below.我知道这很难解释,但请看下面的代码。

Imagine we have simple API using express:想象一下,我们有简单的 API 使用快递:

const app = require('express')

app.get('/endpoint', (request, response) => {
    // code
    response.status(200)
})
app.get('/endpoint2', (request, response) => {
    // code
    response.status(200)
})

Good.好的。 Now I want to authenticate every user which try to request ANY endpoint.现在我想对每个尝试请求任何端点的用户进行身份验证。 Imagine example function below:想象一下下面的示例 function:

// pesudo code

// GET /endpoint2 for example
app.onEvent('request', (request, response) => {
    // some code
    if(something == true){
        // go ahead, execute your request
        request.execute() // redirect to app.get('/endpoint2', ...
    }
    else {
        // authentication failed
        response.status(401).message('Wrong API key or something')
    }
})


// pesudo code

I think I explained it clearly.我想我解释得很清楚。 Thanks for any help.谢谢你的帮助。

This is called middleware .这称为中间件

Write a function that takes a request , response and next arguments.编写一个接受requestresponsenext arguments 的 function。

Call next() when it is done (unless you want to send a response (like Forbidden) instead).完成后调用next() (除非您想发送响应(如 Forbidden)代替)。

Pass it to use .传给use

app.use(yourMiddleware);

It's covered on the second page of the Express.js guide Express.js 指南的第二页对此进行了介绍

You can write any function like this for verification您可以像这样编写任何 function 进行验证

function verify(req, res, next) {
  const bearerHeader = req.headers["authorization"];
  if (typeof bearerHeader !== "undefined") {
    console.log("Auth token", bearerHeader);
  } else {
    res.status(403);
  }
  next();
}

the above one is an example which checks for the Authorization header in the request.以上是检查请求中的授权 header 的示例。 You can write your own conditions.你可以写你自己的条件。 If condition doesn't meet return.如果条件不符合退货。

res.status(403)

and in every request just add this middleware function for verification并且在每个请求中只需添加这个中间件 function 进行验证

app.get('/endpoint', verify,(request, response) => {
    // code
    response.status(200)
})
app.get('/endpoint2',verify, (request, response) => {
    // code
    response.status(200)
})

This will check the call the verification method first and it will verify the written condition and in case of failure it will just return 403 status code and if it pass then这将首先检查调用验证方法,它将验证书面条件,如果失败,它将仅返回 403 状态码,如果通过则

next()

function will get trigger function 将获得触发

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

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