0

I want to submit input value from HTML form to Node.js we have the following files:

  1. app.js
  2. index

output: console.log(“post request made”);

What should I do?

    const express = require('express')
    const app = express()
    
    const bodyParser = require("body-parser");
    app.use(bodyParser.json());
    
    app.use(bodyParser.urlencoded({
      extended: true
    }))
    // app.use(express.urlencoded({
    //   extended: true
    // }))
    
    app.post('/submit-form', (req, res) => {
      const username = req.body.username
      console.log('HASAN');
      res.end();
    })
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      <form method="POST" action="/submit-form">
        <input type="text" name="username" />
        <input type="submit" />
      </form>
    </body>
    </html>
Hasan
  • 60
  • 1
  • 9
  • See the duplicate i have added below @Hasan. That will help you print the console.log() in the browser. – Always Helping Aug 28 '20 at 23:57
  • Should work, but on the browser side you wouldn't see anything, ie a blank page would show as you didn't send anything back to the client. You would only get a console log of `HASAN` on the server. You will need to actually include a problem statement to your question – Patrick Evans Aug 28 '20 at 23:58
  • Does this answer your question? [How to process POST data in Node.js?](https://stackoverflow.com/questions/4295782/how-to-process-post-data-in-node-js) – Always Helping Aug 28 '20 at 23:59
  • You are not sending anything to client so it is showing blank page. Add ```res.send('
    form received
    )``` before res.end().
    – Muhammad Saquib Shaikh Aug 29 '20 at 00:01
  • you can console.log req.body to see what response you got from client. – Muhammad Saquib Shaikh Aug 29 '20 at 00:02
  • _"output: `console.log(“post request made”);`"_ If you want to log a message client side you would need to use some `XMLHttpRequest` or `fetch` request to do that as using a default form request changes the page's location to the action url – Patrick Evans Aug 29 '20 at 00:02

0 Answers0