【问题标题】:Node.js Express – How to Get Raw Data?Node.js Express – 如何获取原始数据?
【发布时间】:2017-12-11 16:01:36
【问题描述】:

我有一个管理登录表单页面的 Express 服务器:

const app = express();

// section A
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.urlencoded());

app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);

它运行正确。

然后我有另一个读取 RAW DATA 的控制器:

// section B
const concat = require('concat-stream');
app.use(function(req, res, next) {
  req.pipe(concat(function(data: any) {
    req.body = data;
    next();
  }));
});

app.post('*', otherController.post);

export let post = (req: any, res: Response) => {
  console.log(req.body); //i see RAW DATA
  res.end('n');
}

它也很好用。

但如果我加入这两个部分,第二部分将停止工作。

我怎么说只能在 B 部分使用req.pipe

【问题讨论】:

标签: javascript node.js express http-post raw-data


【解决方案1】:

这个中间件(就像几乎所有其他中间件一样)没有办法从某些请求中排除它,因为用户希望排除的方法可以是任何东西——url、标题、查询字符串、加载用户等等。取而代之的是中间件将路径逻辑放在您身上:(a)显式包含它(这意味着按照我们的文档中的建议放置在路由上)或(b)用您自己的排除逻辑包装中间件:

const parseExtend = bodyParser.urlencoded({ extended: true });
app.use((req, res, next) => shouldParseRequest(req) ? parseExtend(req, res, next) : next());

/* implement shouldParseRequest (req) to return false for whatever you want to not parse json for */

【讨论】:

    猜你喜欢
    • 2013-09-13
    • 2021-12-23
    • 2013-01-10
    • 2012-03-07
    • 1970-01-01
    • 2014-04-29
    • 2021-06-09
    • 1970-01-01
    • 2014-07-29
    相关资源
    最近更新 更多