Search code examples
node.jsroutesmiddleware

Routing conceptual understanding


I'm creating a Node.js api, and I'm having some difficulty understanding the router middleware. This is my middleware that runs when you hit the api.

app.use("/", index);
app.use("/menu", menu);

index-->index.js; menu-->menu.js
Now, index.js has a signup and signin router, both using POST. This is absent in menu.js

index.js

router.post("/signup", function(req,res){
router.post("/signin", function(req,res){

The problem is as follows:

  • When my URI is at /menu, the correct page is rendered after invoking middleware #2
  • When I hit the signup/signin button, it sends an AJAX post request at /signin or at /signup, whatever the case might be.
  • In my understanding, point #2 should NOT work, since the ajax post request will go to /menu/signup, for which there is NO handler.
    Yet, the handler specified for the POST request in index.js executes, and the user is able to sign in/up even when on the menu page (URL: /menu) after invoking the /menu middleware
    I'm having difficulty understanding WHY this is happening.
    Any help would be great, thanks.


  • Solution

  • I'll post this as an answer since I think it solved your problem.

    If you make an Ajax call from a web page without a leading / on it such as just signup, then the browser interprets that as page relative which means if the page URL is http://localhost/menu and you request an ajax call for signup, then the browser will request a url for http://localhost/menu/signup.

    But, if you prefix your ajax request with / and request /signup, then this is domain-relative so the browser will add the domain and request http://locahost/signup. The path of the current page will not be used. You nearly always want to use the leading / because this gives you a consistent URL request no matter what page you are on.