Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to separate the routes and models from app.js using NodeJS and Express
    primarykey
    data
    text
    <p>I'm creating an app using Node and Express. However, I can see it'll soon become difficult to manage all the routes that are placed inside <code>app.js</code>. I have placed all my models in a subdirectory <code>/models</code>.</p> <p>Here's my app current structure:</p> <pre><code>app.js models -- products -- customers -- ... public views node_modules </code></pre> <p>In <code>app.js</code>:</p> <pre><code>var express = require('express'), routes = require('./routes'), user = require('./routes/user'), http = require('http'), path = require('path'), EmployeeProvider = require('./models/employeeprovider').EmployeeProvider, Products = require('./models/products').Products, Orders = require('./models/orders').Orders, Customers = require('./models/customers').Customers, checkAuth = function(req, res, next) { if (!req.session.user_id) { res.send('You are not authorized to view this page'); } else { next(); } }; var app = express(); </code></pre> <p>Then some configuration like <code>port</code>, <code>views</code> directory, rendering engine, etc.</p> <p>Further down <code>app.js</code> I've got the routes:</p> <pre><code>app.get('/product/edit', auth, function(req, res) { Products.findAll(function(error, prds) { res.render('product_edit', { title: 'New Product', products: prds }); }); }); </code></pre> <p>At the top I'm assigning the contents of <code>models/products.js</code> to a variable, all works fine. However keeping all routes inside <code>app.js</code> is not ideal. But if I move the routes to <code>routes/product.js</code> and load the <code>Products</code> models:</p> <pre><code>var prod = require('../models/products.js'); </code></pre> <p>I get an error saying that object has no method <code>findAll</code>.</p> <p>What am I doing wrong? How can I remove the routes from <code>app.js</code>?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload