its events work. I've written this and I expect it to return my request body as the response, but it gives me this error unncaught (in promise) SyntaxError: Unexpected end of JSON input
but when I put the req.pipe(res) line outside of the event listener block it works as expected, why is that?
const server = http.createServer((req, res) => {
const items = req.url.split('/');
if (req.method === 'POST' && items[1] === 'friends') {
req.on("data", (data) => {
console.log("data")
const friend = data.toString();
firnds.push(JSON.parse(friend));
req.pipe(res)
})
}
my realization is that the request stream comes in chunks and it might contain multiple chunks of data, and the reason for this error is that the req.pipe(res) line gets executed before the entire request is processed. but as you see I've added a console.log("data") to log whenever a chunk of data arrives, and it only happens once. doesn't that mean that the entire request body is passed in one chunk and it should work ok? again, the code works well when I put the req.pipe(res) line outside of the event listener block.
That's not going to work
Обсуждают сегодня