How to submit a form from HTML to a Node.js file

I have an HTML file called index.html and Node.js files called server.js and logic.js.

server.js is not acceptable for creating a server and loading the index.html file. The HTML file displays a form requesting any action (for example: username), then it sends this data to the logic.js file that prints this username.

How can I do that? Thanks!

+3
source share
1 answer

Well, without seeing any code or not knowing which framework you are using, it will be difficult to be specific, but you will want to

  • Extract HTML containing form on HTTP GET
    • This is the simplest part. Just write a simple document with one or more tags. I assume that you already have a web server that does this.
  • Listen to POST requests.
    • This is different from GET, and your server will most likely have a different function to handle this request (since the logic is different).
  • Handle POST requests
    • here you just want to pull the name from the POST data and print it (or do whatever you want).

I recommend using expressjs , since you probably don't want to write all the code that processes the web server. In this structure, rendering HTMl is simple, like

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

and POST processing will be as simple as

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

edit: to answer your question, it’s actually not so difficult to decompose the logic of processing multiple pages in separate files. What I usually do is server.js, which installs everything and then will include other files that handle the logic for other pages.

For example, if your application can be laid out as

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

and server.js will include all the files inside the modules directory, one of them may 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"); }); 
+4
source

Source: https://habr.com/ru/post/955629/


All Articles