Reputation: 113
i have question about routing in sails.js. So, i'm following a tutorial about making a login page. it consists of AuthController.js
module.exports = {
login: function(req , res){
res.view('login'); //view login page
},
authenticate: function(req, res) {
//some auth function
}
};
login.ejs
<div id="login">
<form align="center" action="/login" method="post">
<ul>
<li>
<input type="text" name="username" placeholder="Username"></li>
<li>
<input type="password" name="password" placeholder="Password" ></li>
<li>
<input type="submit" value="Log In"></li>
</ul>
</form>
</div>
and finally this is what makes me confused in routes.js
. why this works?
'get /login': {
controller: 'AuthController',
action: 'login'
},
'post /login' : {
controller: 'AuthController',
action: 'authenticate'
},
but this doesn't (i removed the get)?
'/login': {
controller: 'AuthController',
action: 'login'
},
'post /login' : {
controller: 'AuthController',
action: 'authenticate'
},
when i'm using the later route it seems that authentication
action is never called when i enter username password, and it's just redirecting me to login page again (it's calling login
action instead).
Upvotes: 0
Views: 428
Reputation: 5671
As others have said, it's because the routes are compared in order, triggering whichever matches first.
Interestingly that means that if you swap the order, it works as you described:
'post /login' : {
controller: 'AuthController',
action: 'authenticate'
},
'/login': {
controller: 'AuthController',
action: 'login'
},
Upvotes: 1
Reputation: 6760
In sails Js, route.js consists of an address (on the left, e.g. 'get /login') and a target (on the right, e.g. 'AuthController.login'). The address is a URL path and (optionally) a specific HTTP method. When Sails receives an incoming request, it checks the address of all custom routes for matches. If a matching route is found, the request is then passed to its target.
Now, when you remove the get option, & lift your app, & navigate to /login, first the login page is rendered but when the form is posted, it's unable to differentiate b/w the requests as you have omitted get request, so it again calls /login & never reach on the post route.
Reference :http://sailsjs.org/documentation/concepts/routes
Upvotes: 0
Reputation: 1152
From the sails documentation:
If no verb is specified, the target will be applied to any request that matches
the path, regardless of the HTTP method used (GET, POST, PUT etc.).
URLs are matched against addresses in the list from the top down.
Also the order works from top to bottom. So when you try to POST in /login
, it again goes to /login
rather than POST /login
.
Hope this helps.
Upvotes: 3