1
    const http = require('http');
const fs = require('fs');
const url = require('url');
const hostname = 'xxxx';
const port = xxxx;


const server = http.createServer((req, res) => {
    let parsedUrl = url.parse(req.url, true);
    var qdata = parsedUrl.query;
    let n = parseInt(qdata.n);
    console.log(n);
    if (n <= 0) {
        res.writeHeader(500, {
            'Content-Type': 'text/plain',
        });
        res.write("Fuer n wurde kein gueltiger Parameter uebergeben!");
    }
    else {
        res.writeHeader(200, {
            'Content-Type': 'text/plain',
        });
        function fibonacci(num) {
  if (num <= 1) return 1;

  return fibonacci(num - 1) + fibonacci(num - 2);
}
        res.write("Die " + n + "-te Fibonacci Zahl lautet " + fibonacci(n));
    }


    res.end();
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

if i run this code, i get the error RangeError: Maximum call stack size exceeded. But why? It happened when i called it with 9, fibonacci shouldnt be a problem at such a small number.

4
  • Hi, you seem to be missing some code (I am getting a syntax error) Commented Nov 24, 2021 at 12:32
  • 1
    What happens when you call it with 1? (And how are you calling it?) Commented Nov 24, 2021 at 12:32
  • What value of of num are you inputting? Commented Nov 24, 2021 at 12:33
  • the thing is this: when i call it the first time, it shows me the right value. but if i try it a second time, i get the error. Commented Nov 24, 2021 at 12:39

1 Answer 1

2

There are two problems here: 1. getting it to run, 2. getting it to run properly.

1. You are incorrectly parsing data, such that let n = parseInt(qdata.n); gives you back undefined. The callback is the function that is executed once the server starts. This means that even before you have inputted a number, your server is running the fibonacci sequence.

Because it's already parsing data, it parses n, which, of course, is undefined. Parsing this into an Int, you get NaN. This is a problem because Nan-1 or Nan-2 always returns Nan, meaning that you enter into an infinite upon start of the server.

To fix this, you should check whether n exists:

if(String(n) !== String(NaN) {
  ...
}
  1. Efficiency: calculating the fibonacci sequence like this will cause a huge problems down the line. I would take a look at dynamic programming.
Sign up to request clarification or add additional context in comments.

1 Comment

worked, thank you!

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.