apprentice edu
apprentice edu

Reputation: 11

What is wrong with this Node.js snippet?

I am learning node.js and the course says there is something wrong with the following snippet.

const fs = require('fs');
const http = require('http');
 
const server = http.createServer((req, res) => {
  if (req.headers['x-secret'] != process.env.SECRET )
    res.writeHead(403).end('Secret incorrect');
 
  let body = [];
  req.on('data', chunk => {
    body.push(chunk);
  });
  req.on('end', () => {
    body = JSON.parse(Buffer.concat(body).toString());
    fs.writeFileSync(body.filename, body.file);
    res.writeHead(200).end('OK');
  });
});
 
server.listen(7654);

Possible things I've found include:

However the course seems to be saying that there's a big mistake, which I can't really find.

Please help!

Thanks

Upvotes: 0

Views: 66

Answers (2)

Sushilzzz
Sushilzzz

Reputation: 577

The only problem i see here is in the line

let body = [];

you cannot initialize body as an empty array as you are using it as an object in line

fs.writeFileSync(body.filename, body.file);

you cannot do body.filename as dot notation is only used in an object.

Upvotes: 0

Tigran Vardanyan
Tigran Vardanyan

Reputation: 46

Buffer.concat(body).toString() is not valid JSON, so You can't parse it. what you will receive if you log it

----------------------------118769234111712879210320
Content-Disposition: form-data; name="data"; filename="test.json"
Content-Type: application/json

{
    "test": "156"
}
----------------------------118769234111712879210320--

like this

Upvotes: 1

Related Questions