0

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:

  • https should be used instead of http (secure server)

  • Res.writeHead.end is not valid syntax. Res.writeHead and res.end
    should be written separately

  • fs.writeFile() should be used, not the async version

  • There's no failsafe built-in (?)

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

Please help!

Thanks

3
  • 1
    Maybe the fact that your condition statement doesn't actually prevent parsing the request body in the event that the secret is unspecified or wrong? Commented Jan 8, 2023 at 1:04
  • doesn't res.writehead(403).end('Secret incorrect') do that? Commented Jan 8, 2023 at 10:27
  • There's no return statement, so no, it doesn't. The program still processes the request, parses it, then invalidly calls res.writeHead(200).end('OK'); Commented Jan 8, 2023 at 17:37

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Welcome to StackOverflow! Please provide a possible solution in addition to a description of the problem.
0

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.

2 Comments

Notice body gets reassigned before that line with a call to JSON.parse(...)
@PatrickRoberts Lol, I didn't see that. I never reassign. so what's wrong here? I mostly use express

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.