Home > Software engineering >  In Nodejs http server req.on('data') is not fireing
In Nodejs http server req.on('data') is not fireing

Time:09-03

I am learning Nodejs. I am trying to learn how the read stream works in the HTTP server in Node js. This is my code.Here is the req.on('data') event is not firing.Please help me if you can. Thank you.

Code-

const http = require('http');

const server = http.createServer(onConnect);
server.listen(3000);

const homePage = `
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <form action="/process" method="post">
      <h3>Enter your text here</h3>
      <br />
      <input type="text" />
    </form>
  </body>
</html>


`;

function onConnect(req, res) {
    if (req.url === '/') {
        res.write(homePage);
    } else if (req.url === '/process' && req.method === 'POST') {
        req.on('data', (chunck) => {
            console.log(chunck);
        });
        res.write('<h1>Thank you for your submission</h1>');
    } else {
        res.write('No page found');
    }
    res.end();
}

CodePudding user response:

As @robertklep correctly pointed out, you need to define the name attribute on your input element.

However you also need to define the 'end' event on the request object in order for your code to work. A typical setup for this would look like this:

function onConnect(req, res) {
    if (req.url === '/') {
        res.write(homePage);
    } else if (req.url === '/process' && req.method === 'POST') {
        let requestBody = "";
        req.on('data', (chunck) => {
            requestBody  = chunck;
        });
        req.on('end', () => {
            console.log(requestBody);
        });
        res.write('<h1>Thank you for your submission</h1>');
    } else {
        res.write('No page found');
    }
    res.end();
}

CodePudding user response:

If you don't provide a "name" attribute for a form element, your browser will not post it.

So try this:

<input type="text" name="mytext" />
  • Related