Dirk
Dirk

Reputation: 3221

Basic Express Routes

How do I get the following routes to work in Express:

/ (get and post)
/users (get and post)

Right now, when I visit /users, the page renders correctly, but on submission, it runs the code in /index (post route) instead of the code in /users (post route).
My files look like this: users.js:

router.get('/', function(req, res, next) {
var title = 'users';
res.render('users');
});

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

index.js:

router.get('/', function(req, res, next) {
    var title = 'index';
    res.render('index');
});

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

app.js:

var routes = require('./routes/index');
var users = require('./routes/users');
var show = require('./routes/show');

and in the app.use section:

app.use('/users', users);
app.use('/show', show);
app.use('/', routes);

EDIT:
Form action is:

form(method="POST", action="/post")

Upvotes: 0

Views: 94

Answers (1)

Brennan
Brennan

Reputation: 1785

Like Nicholas has said in the comments, you should update your form to as follows:

Form

form(method="POST", action="/users")

This will hit your POST route in your users controller.

If you also desire a POST to / as well, you should update your index.js to:

Index.js

// it should be / not /post
router.post('/',function(req,res){ ... }

Also, be aware you'll probably need to use body-parser to parse out the Form data.

Hope this helps!

Upvotes: 1

Related Questions