Confusion over app.post action and form action

This is a link to my project: https://glitch.com/edit/#!/gli-forktery
I am trying to pass input from a client side form to my client side scripts to be consumed and sent to a database. A tutorial I found directs me to make the action of the text form “/posts/input” and then create an app.post action also called “/posts/input”. I then log req.body to the console (I have body-parser installed). However, nothing happens. What am I missing? The code is below.

app.post("/posts/input",  (req, res) => {
  req.body
  console.log(req.body)
})

--- --- -- 
 <input type="text" name="body" action="/posts/input" method="POST">

1 Like

Additionally, I am unable to connect to my MongoDB database even though my code works in other cloud distros (like Repl.it)

Hi,

I remixed your project, you can find the link here: https://glitch.com/edit/#!/abstracted-pickle-galliform

The problems with the POST request:

  1. you need to explicitly use the body-parser package to parse the incomming POST requests, like this:
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
  1. put the action and method attribute into you form tag in the ejs template, similar like this:
<form action="/posts/input" method="POST"> 
    <label for="body">Body Input </label >
    <br>
    <input type="text" name="body">
    <button type="submit">
         Submit
    </button>
</form>

Check out the project link above, I have created a working example.

3 Likes

Thanks! However, I am confused about the function of action="/posts/input". When I was learning to write forms in HTML I always assumed that this was a link to a file path. However, this is not the case in the examples I have seen and your reply. What does action="... actually do?

action specifies where to send the form data. It is a URL that the web application listens to and is able to serve incoming requests to.

I assume you worked with php backends earlier, because in case of php, the post action can look something like this:

<form method="POST "action = "/post.php">
...
</form>

This means that the form data will be sent to the server with path /post.php, and you need to have a post.php file to handle it.
In case of nodejs and express, you can define routes to handle POST and GET (and other types) requests:

...
app.get('/',(req,res,next)=>{res.send('ok')})
app.post('/posts/input',...
...

And you can user these routes in your form to send data to your server.

1 Like

Ah I see. No , I haven’t worked with PHP - the w3schools examples always defined a php path though. So in the example of NodeJS, the action is not a path but a rout for your code to listen to. Thanks for clarifying!

1 Like