Islam Hassan
Islam Hassan

Reputation: 1736

How to post a form from HTML into Node.js file

I've a HTML file named index.html, and a Node.js files named server.js and logic.js.

server.js is reponsible for creating the server and loading index.html file. The HTML file displays a form asking for any action(ex: username), then it posts this data to the logic.js file which prints this user name.

how could it be done? Thanks!

Upvotes: 3

Views: 3293

Answers (1)

tjarratt
tjarratt

Reputation: 1690

Well, without seeing any of your code or knowing what framework you're using, it will be hard to be specific, but you'll want to

  • Render some HTML that includes a form on HTTP GET
    • this is the simplest part. Just write a simple document with a and some tags. I assume you already have some web server that does this.
  • Listen for POST requests.
    • This is different from a GET and your server will likely have a different function to handle that request (because the logic is different).
  • Handle the POST requests
    • here you'll just want to pull out the name from the POST data and print it (or do whatever you want).

I recommend using expressjs for this since you probably don't want to write all of the code that handles the web server. With this framework, rendering HTMl is as simple as

app.get("/", function(request, response) { res.send(some_html); });

and handling the POST would be as simple as

app.post("/endpoint", function(request, response) { console.log(request.query.name); });

edit: to answer your question, it really isn't that hard to spread out the logic for handling multiple pages throughout separate files. What I normally do is have a server.js that sets up everything, and then will include the other files that handle the logic for other pages.

For example, if your app might be laid out like

server.js
/modules/
/modules/index.js
/modules/user.js
/modules/posts.js
public/index.html
public/user.html
public/posts/html

and server.js would include all of the files inside the modules directory, one of them might look like

index.js

app.get("/", function(req, res) {
  render("index.html");
});

user.js

app.get("/user", function(req, res) {
render("user.html");
});

post.js

app.get("/post", function(req, res) {
render("post.html");
});

Upvotes: 4

Related Questions