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.
CodePudding user response:
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) {
...
}
- Efficiency: calculating the fibonacci sequence like this will cause a huge problems down the line. I would take a look at dynamic programming.
CodePudding user response:
Maybe qdata.n
is undefined.
parseInt(undefined)
is NaN
(Not a Number)
parseInt(undefined) <= 1
is false
So it loops endlessly.
Same for:
parseInt(null)
is NaN
parseInt('')
is NaN
Just check:
let n = parseInt(qdata.n);
console.log(n);
if (!Number.isNaN(n) && n <= 0) {
// ...