Something that I wanted clarification on is when console.logging req.body in my express app. I end up with a buffer/string or hexadecimal of some sort when I'm expecting an JSON object. I'm using postman to send a raw json body. Here are some visuals of the source code and terminal/postman results.
const express = require('express');
const bodyParser = require('body-parser');
const { randomBytes } = require('crypto');
const app = express();
app.use(express.raw({type: "application/json"}));
app.use(express.json({strict: false}));
app.use(express.urlencoded({extended: false}));
const posts = {};
app.get('/posts', (req, res) => {
res.send(posts);
});
app.post('/posts', (req, res) => {
const id = randomBytes(4).toString('hex');
const { title } = req.body;
console.log(req.body)
posts[id] = {
id,
title: title
};
res.status(201).send(posts[id]);
});
app.listen(4000, () => {
console.log('Listening on 4000');
});
app.use(express.raw({type: "application/json"}));
is going to give you a Buffer object and since that's your first middleware that might handle that mime type, that's what you're going to get for any application/json
request.
Right from the Express doc for express.raw()
:
This is a built-in middleware function in Express. It parses incoming request payloads into a Buffer
It's unclear why you're using express.raw()
as that is not typical for JSON payloads, but when doing so, you are going to get a Buffer
- that's how it works. One would more typically use express.json()
for JSON payloads and let it parse your JSON so that req.body
contains an actual Javascript object.
If you remove the app.use(express.raw({type: "application/json"}));
line of code and let the app.use(express.json());
line of code right after it handle the application/json
payloads, then you will get your parsed data in req.body
.
Keep in mind that when using middleware they are processed in the order declared and for this specific type of middleware, the first one that matches and reads the body from the incoming stream takes precedence and none of the others after it will be able to do their job (since the incoming stream has already been read).