简体   繁体   中英

Why i don't read data at POST

i learn node and have problem. why i don't read data at my POST request? When i send my POST at html, if with req.method POST is work, but emmit 'data' doesn't work. This is part of my html:

<form method="post" action='./script.js'>
<label for="my-form">Enter phraze</label><input type="text" id='my-form'><br>
<input type="submit">
</form>

let fs   = require('fs');
let http = require('http');

let server = http.createServer( (req, res) => {

  res.setEncoding = 'utf8';
  res.writeHead(200, {'Content-type': 'text/html'});

  if(req.url == '/'){
   reply('./index.html', res)
  }
  if(req.method == 'POST'){
   let body;
   req.on('data',
    (chunk) => { if(chunk != null) {body += chunk.toString(); res.write(chunk.toString())} })
   req.on('end',
    () => res.end(body) )
 }

}).listen(5858);

server.on('error', (err) => { throw err.message });

function reply(path, res){
  let streamPage = fs.createReadStream(path, {encoding: 'utf8'});

  streamPage.on('readable',
    (chunk) => { chunk = streamPage.read(); if(chunk != null) res.write(chunk) });
  streamPage.on('end',
    (out) => res.end());
  streamPage.on('error', (err) => err.message)
}

You send post request to script file, it's not correct. You should set route to you server in action field.

<form method="post" action='/'>
<label for="my-form">Enter phraze</label><input type="text" id='my-form'><br>
<input type="submit">
</form>

Something like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM