-1
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });

});
router.post('/', function(req, res, next){
res.send("post works");
});

module.exports = router;

This is my index.js file. I used express to create an app, add my own jade file which has a form in it. Can i define a post method like that? I am new to node.js so dont really have a grasp on how this works?

I would like to add i am trying to save data to a mongodb instance.

Update: 26/11/18

I got the solution after i got the answers given down below, I am adding the GitHub link.

I have added the working files to it.

Harsh Patalia
  • 173
  • 1
  • 10

2 Answers2

0

Below is an example html login form, to make a post route work you have to make sure you define method="POST" and action="/(Insert Route)". In my example action="/login", this means that there would be a post request that is sent to /login. If I had a router setup that accepted all /login requests it would be redirected there and the router.post('/') would work.

<form action="/login" method="POST">
    <p">Username</p>
    <input type="text" name="username" placeholder="Enter Username">
    <p>Password</p>
    <input type="password" name="password" placeholder="Enter Password">
    <input type="submit" name="" value="Login">
</form>
Eric Leus
  • 57
  • 10
0

After searching the web for clarification at the end both the answers helped me out. I was trying to do a POST request from my route, i had the variable "router". What I overlooked was to add the function name to it. My html form was trying to submit to a function "/login" and My router did not have the function defined.

router.post('/login', function(req,res, next){
}

This did it. Thanks to everyone that tried to help.

Harsh Patalia
  • 173
  • 1
  • 10