Nooa
Nooa

Reputation: 21

Why doesn't post method do anything?

I am trying to make a server that uses simple routing without using a framework and saves received data to a file. In order to do that I ought to be able to get my submit-button to do something, but now it seems it doesn't.

 const http = require('http');
 var url = require('url');
 const hostname = '0.0.0.0';
 const port = 3000;

 const server = http.createServer((req, res) => {
 if(req.url == "/save"){
    if(req.method === 'POST'){
        console.log("Why, why, nothing happens?.");
        res.end("What is wrong?");
    }
    else{
        res.end(`
            <!doctype html>
            <html>
            <body>
                <form action="/" method="post">
                    <input type="text" name="data" /><br />
                    <button>Save</button>
                </form>
            </body>
            </html>
        `);
    }
  }
 });

 server.listen(3000);

Upvotes: 0

Views: 53

Answers (1)

Quentin
Quentin

Reputation: 944443

This is the URL you are POSTing to:

action="/"

This is a simplified version of your code:

if(req.url == "/save"){
    // Do something
}

It does nothing because it doesn't pass your if condition ("/" !== "/save"!) and you don't have an else branch.

Upvotes: 2

Related Questions