Search code examples
javascriptnode.jsexpresssingle-page-application

How do I organize my api routes vs my page routes in a SPA?


Let's say I have a resource squids.

There is a page in my app to add squids with a form describing their inkiness etc, I'd say this form should be at localhost/squid.

Then the post req to make a new squid goes to the same place localhost/squid.

But what about when I want to GET a list of all squids? How do you/should I structure and name these similar routes?

i.e.

 // app/routes/squid.js

 router.get('/', (req, res) => res.render('squid'));

 router.post('/', (req, res) => {
     saveSquid();
     res.render('dashboard');
 });

Solution

  • I would suggest adding a prefix to all of your api calls as following:

    GET /api/squids // will get squids back 
    

    and then you can still use /squids to render the page.

    you can also use express router module to make a different router for the api:

    var app = express();
    var apiRouter = express.Router();
    apiRouter.get('/squids', function(req,res){});
    
    var pubRouter = express.Router();
    pubRouter.get('/squids', function(req, res){})
    app.use('/api', apiRouter);
    app.use('/', pubRouter);