Home > Mobile >  Express JSON parse by JSON and by text
Express JSON parse by JSON and by text

Time:06-09

I currently have 2 consumers of the same, Express JS, API. When I run my API locally I have to specify either:

app.use(express.text);

or:

app.use(express.json);

Depending on what content-type is being sent to the API. Is there a way I can handle both content-types or contextually handle the contents of the request as currently I can only use one or the other and not both at the same time.

CodePudding user response:

You can specify both:

app.use(express.text(), express.json());

(don't forget the parentheses).

The text() middleware parses the incoming request only if Content-Type: text/plain, whereas json() parses only Content-Type: application/json. This is important, because every incoming request can be parsed only once. After req.body has been filled by the text() middleware, say, the entire request payload has been consumed, and subsequent middlewares cannot consume it again.

  • Related