繁体   English   中英

Node.js Express –如何获取原始数据?

[英]Node.js Express – How to Get Raw Data?

我有一个管理登录表单页面的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);

它可以正常运行。

然后,我还有另一个读取原始数据的控制器:

// 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

该中间件(几乎像其他所有中间件一样)没有一种将其从某些请求中排除的方法,因为用户希望排除的方法可以是任何东西-网址,标头,查询字符串,加载的用户和更多。 相反,中间件将路径逻辑放在您身上:(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 */

暂无
暂无

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

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