user3248186 user3248186 - 1 year ago 53
Node.js Question

How to use post in nodejs?

I have trouble understanding how to use post in nodejs. I understood that get is mainly used to render a page. But how is post working in this sample application?

var express = require("express");
var bodyParser = require("body-parser");
var app = express();

app.use(bodyParser.urlencoded({ extended: false }));

var user_name=req.body.user;
var password=req.body.password;
console.log("User name = "+user_name+", password is "+password);
console.log("Started on PORT 3000");

Here is the data being sent to localhost:3000/login?

If so, why do I get a 404 network error with Cannot GET /login when I go this url?

What exactly happens here? Please explain.

Answer Source

When you type in 'localhost:3000/login' into a web browser it's going to use the HTTP get method. There are many HTTP methods such as post, put, get, etc.

Now when you submit like an HTML form or something that normally does a HTTP post method and sends data to the server.

So since you don't have a get method for /login you get a 404 error since it's post not get.

For example using the following HTML code would send a post request to /login when you submit the form.

<form action="/login" method="post">
  <input type="text" name="user"><br>
  <input type="text" name="password">

Submitting that form should console.log the username and password you type in. The name attribute on the HTML form corresponds to the req.body.password variable in your code. So if you changed password to something else on the form or on the express code it wouldn't work and would be undefined.