首页 > 解决方案 > 如何在 express.static 中提取请求标头

问题描述

我正在使用 express.static 中间件,因为我不想在路由中单独列出每个资产。当我使用 Vue JS 时,我所有的路由都是通过 index.html 处理的。

由于功能要求,我需要从请求标头中提取一些信息,但我在 express.static 的选项或文档中都没有看到请求。

这是我的代码

const staticFileMiddleware = express.static(__dirname);
app.use(staticFileMiddleware);
app.use(history({
  disableDotRule: true,
  verbose: true
}));

// here I wanted to print out req.headers but its not available anywhere
// console.log(req.headers); <------------------------------

const port = 8080;
app.listen(port, () => {
  console.log(`Example app listening on port ${port}!`);
});

标签: javascriptnode.jsexpressvue.js

解决方案


您需要创建一个中间件:

app.use(function (req, res, next) {
  console.log(req.headers)
  next()
})

推荐阅读