0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.jsのExpressでbody-parserを使いたくないけど特定のハンドラーでだけボディのパースをしたい

Posted at

特定のURL以下だけパースしたいが、その他の広いパスではパースしたくないみたいなことが5年に1度ぐらい発生するかもしれないので、そのやり方のメモ。例えば99%のリクエストはプロキシーとしてそのまま他のプロセスに流す場合、パース作業はほぼ無駄になってしまうので必要なところでだけやりたいですよね?routerを作ってその下だけbody-parserを適用とかできるならそれでもいいかもしれませんが、微妙にそれもしにくい・・・みたいな場合に。

app.ts
import express, { Request, Response } from 'express';
// 本当はimportしなくてもいいはずだけどTypeScriptはimportしないとエラーになるっぽい
import { URLSearchParams } from 'url';

app.post('/form/receive', (req: Request, res: Response) => {
    let body = '';
    // streamのAPIを直接扱ってdata/endで情報を読み込む
    req.setEncoding('utf8');
    req.on('data', (chunk) => {
        body += chunk;
    });
    req.on('end', () => {
        // フォームのポストを受け取るのでURLSearchParams.
        // JSONならJSON.parse
        const params = new URLSearchParams(body);
        console.log(params); // パースできてる!
        res.end();
    });
});

const port = process.env.NODE_PORT || 3000;
console.log(`listening at ${port}`);`
app.listen(port);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?