Skip to content

Commit b33e2f0

Browse files
committed
Refactor body parsing to use Buffer.concat for proper UTF-8 support
1 parent 94c45fa commit b33e2f0

1 file changed

Lines changed: 5 additions & 4 deletions

File tree

‎middleware-exercise/two-custom-written-middlewares.js‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,25 +17,26 @@ const usernameMiddleware = (req, res, next) => {
1717
};
1818

1919
const arrayMiddleware = (req, res, next) => {
20-
const bodyBytes = [];
20+
const chunks = [];
2121

2222
// Every time a piece of data arrives, we put it in our list
2323
req.on("data", (chunk) => {
24-
bodyBytes.push(...chunk);
24+
chunks.push(chunk);
2525
});
2626

2727
// When the whole message has arrived, we process it
2828
req.on("end", () => {
29-
const bodyString = String.fromCharCode(...bodyBytes);
29+
const bodyString = Buffer.concat(chunks).toString();
3030

3131
let bodyObject;
3232
try {
3333
bodyObject = JSON.parse(bodyString);
34+
3435
} catch (error) {
3536
res.status(400).send("Invalid JSON");
3637
return;
3738
}
38-
39+
3940
if (
4041
Array.isArray(bodyObject) &&
4142
bodyObject.every((item) => typeof item === "string")

0 commit comments

Comments
 (0)