node.js

express middleware

const express = require('express');
const app = express();

app.use((req, res, next) => {
console.log(req);
next();//app.use()表示每次调用应用程序都会调用此中间件。
});

app.get('/', (req, res, next) => {
res.send('Welcome Home');
});

app.listen(3000);

该app.get()功能是应用程序级中间件。你会注意到传递给方法的参数是req,res和next。这些是传入的请求,正在写入的响应,以及一种在当前中间件完成后将调用传递给下一个中间件功能的方法。在这种情况下,发送响应后,该函数将退出。您也可以在此处通过调用next()方法链接其他中间件。

2

const express = require('express');
const app = express();

const requireJsonContent = () => {
  return (req, res, next) => {
    if (req.headers['content-type'] !== 'application/json') {
        res.status(400).send('Server requires application/json')
    } else {
      next()
    }
  }
}

app.get('/', (req, res, next) => {
  res.send('Welcome Home');
});

#第三个参数是next()中间件接下来的处理,第二个参数requireJsonContent()是post请求对应的方法
app.post('/', requireJsonContent(), (req, res, next) => {
  res.send('You sent JSON');
})

app.listen(3000);

https://thehackerish.com/the-top-9-bug-bounty-resources-to-stay-up-to-date/

posted @ 2020-09-07 16:55  blog_hfg  阅读(75)  评论(0)    收藏  举报