Reputation: 1558
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 }));
app.use(bodyParser.json());
app.get('/',function(req,res){
res.sendfile("index.html");
});
app.post('/login',function(req,res){
var user_name=req.body.user;
var password=req.body.password;
console.log("User name = "+user_name+", password is "+password);
res.end("yes");
});
app.listen(3000,function(){
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.
Upvotes: 0
Views: 84
Reputation: 1567
The route is built in 2 parts, the verb (GET, POST, PUT, PATCH, DELETE) and the "uri"
In your code you have the post login route which should process the identification of the user. In your case simply console log the username and pass. You would surely create a session then redirect the user. So this route could has no view.
Your 404 comes from the fact you don't have a route for displaying your login form. Assuming you want a dedicated page for that. You have to create a GET /login route then creating a view for that route.
If you plan to display you login form in the header or in a sidebar you won't need a GET /login route.
Upvotes: 0
Reputation: 20496
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">
Username:<br>
<input type="text" name="user"><br>
Password:<br>
<input type="text" name="password">
</form>
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.
Upvotes: 1