I'm in the process of refactoring my server.js file and trying to incorporate MVC pattern. I'm running into a problem trying to access my controller from my routes.js. I've tried just about every variation of absolute and relative path that I can think but I must be missing something.
Here is my directory structure:
And from my routes.js, here is my code:
module.exports = function ( app, passport, auth ) {
var Clients = require('controllers/clients');
app.get('/clients', Clients.list);
}
I don't think this is relevant, but here is my clients controller:
var mongoose = require('mongoose')
, Client = mongoose.model('Client');
exports.list = function( req, res ) {
Client.find( function( err, clients ) {
res.renderPjax('clients/list', { clients: clients, user: req.user });
});
}
Here is the error that I'm getting when trying to access my controller from routes:
module.js:340
throw err;
^
Error: Cannot find module 'controllers/clients'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at module.exports (/Users/sm/Desktop/express3-mongoose-rememberme/app/routes.js:5:16)
at Object.<anonymous> (/Users/sm/Desktop/express3-mongoose-rememberme/server.js:334:24)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
I'm sure it's something simple that I'm over looking. How can I access my controller from
my routes?
To require something that isn't a separate package (isn't in node_modules), you need to use an explicitly relative path:
require('./controllers/clients')
For more information, see the documentation.
Local Modules
require(...) takes a relative path for local modules
require('./controllers/clients')
Installaed modules
For modules installed via npm install -S foo, use the syntax
require('foo')
Related
Im Learning to make a web application with Node.js Express JS.
When I run my server.js
$ node server
I get this
Error: Cannot find module './config/express'
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/Users/david/Desktop/Node/ejemplo/server.js:2:18)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
my server.js file is like this...
server.js:
var express = require('./config/express');
var app = express();
app.listen(3000);
module.exports = app;
console.log('Server running at http://localhost:3000/');
before doing this I run this command in the root of my app
npm install
Here is a like to a picture to show you the project folder structure I have.
I dont understand why cannot find module './config/express' while apparently the folder structure is fine.
Any idea??
I dont understand why cannot find module './config/express' while apparently the folder structure is fine.
after installing npm, you should try express installation into your project directory as
npm install express
it will create node_modules of express.
then you should use
var express = require('express');
Your server.js doesn't work because express.js file into config folder create confusion.
Change the name from express.js to init.express.js
and then it will work.
I'd like to know if it's possible to change the context from where the Express server is serving from, to avoid issues in the import/require files in the App that is served.
I'm serving from [root]/server.js, this file checks for the process.env.NODE_ENV and then requires a file in let's say ./dist/ENVIRONMENT/server.js
if (['staging', 'production'].indexOf(process.env.NODE_ENV) > -1) {
require('./dist/' + process.env.NODE_ENV + '/server.js')
} else {
require('babel-register')
require('./server.dev.js')
}
The files that are served are triggering an error related with the import/require locations that fails for the reason explained in the previous paragraph
Error: Cannot find module '../../../../xxxxx'
Why am I doing this? I'm transpiling the server source code for non development (that runs with babel) and then copied to the distribution directory. I understand that I can have tasks to rename and move this accordingly during deployment, that also solves the problem, but I'd like to learn or understand if we're able to change the context where the Express server, serves from!
From the top of my head, I guess I'll have to solve it through something like (which I'll be testing):
var dist = path.resolve(__dirname, '../../')
app.use(express.static(dist))
Which I attempted, but failed, same error:
Error: Cannot find module '../../../../config'
at Function.Module._resolveFilename (module.js:485:15)
at Function.Module._load (module.js:437:25)
at Module.require (module.js:513:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/Users/xxxx/www/projectFoobar/dist/staging/lib/services/foobarService/index.js:13:15)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
The config file happens to be in the [root] directory.
** OK just realised that using import/export is a bad practice
https://nodesource.com/blog/es-modules-and-node-js-hard-choices/
I have a node.js app which uses express and runs locally with no problems. However, on Azure I am seeing:
Application has thrown an uncaught exception and is terminated:
Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\home\site\wwwroot\server.js:1:79)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
The packages.json file contains the dependency:
"express": "^4.15.3"
Assuming something had gone wrong with the npm install, I went to the Kudu remote execution console and ran npm outdated. No packages are missing.
This is my server.js file:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.port || 8000;
app.use(bodyParser.urlencoded({ extended: true }));
require('./app/routes')(app);
app.listen(port, () => {
});
I'm assuming it is something very obvious, but I can't work out what I'm missing.
Assuming your Azure App Service is Windows environment, try to include node_modules in the wwwroot.
There isn't much we can really help with here, as the error you have provided indicates that the express npm package has not been installed properly. So, I would suggest that you use App Service Editor (https://[YouAppName].scm.azurewebsites.net/dev/wwwroot/) to troubleshoot this issue by checking whether the express folder exists in the node_module.
You can also run command npm install in the console, restart your app and run it (Ctrl + F5) in the browser.
I'm new at this, I'm trying to absorb as much as possible.
I am using this template https://github.com/primaryobjects/Node.js-Bootstrap-Starter-Template
Okay, all right till here, but when I try to add a new page, it returns me the following error:
C:\server\node_modules\express\lib\router\route.js:196
throw new Error(msg);
^
Error: Route.get() requires callback functions but got a [object Undefined]
at Route.(anonymous function) [as get] (C:\server\node_modules\express\lib\r
outer\route.js:196:15)
at EventEmitter.app.(anonymous function) (C:\server\node_modules\express\lib
\application.js:481:19)
at Object.<anonymous> (C:\server\app.js:31:5)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
The aim would be to answer me a new page at the following address:
http://localhost:3000/ask?america=
The steps I followed were:
Create a view and a path
/views/ask.jade
extends layout
block content
div.container
h1 ASK
2n
/routes/ask.js
exports.ask= function(req, res){
res.render('ask');
};
3r
app.js
app.get('/ask', routes.ask);
But when I try to start "node app" returns me the error mentioned above.
Where am I mistaken?
Have you tried requiring specifically your routes/ask.js file? I'm pretty certain when using
require('folder')
require looks directly for an index file and uses that index file which I believe may mean that your routes/ask.js file might actually not be getting "required" by the app.
So
var askRoutes = require('./routes/ask')
...
...
app.get('/', routes),
app.get('/ask', askRoutes)
To modularize your code you could utilize your routes/index.js file as a routes module load file, where you load your route modules (like routes/ask.js) into your index file so you won't get bogged down by having a ton of required route modules in your app.js file. Just the index.js file would be required.
Can you try the followings :
use the default route first : app.get('/', routes.index); and then put your code after app.get('/ask', routes.ask);
if it doesn't work, put instead of res.render('ask'); the minimal return res.send('some json');
I'm trying to run Mike Wilson's book sample app, but receiving the following error:
pcassiano#...:~/socialnet$ sudo node app.js
/home/pcassiano/socialnet/app.js:60
require('./routes/' + routeName)(app, models);
^
TypeError: object is not a function
at /home/pcassiano/socialnet/app.js:60:35
at Array.forEach (native)
at Object.<anonymous> (/home/pcassiano/socialnet/app.js:57:26)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
i'm running the latest code from the book's repo.
what should i do in order to run this sample app properly?
thanks in advance.
You likely have .js files in the routes directory that do not export a function.
app.js is calling require on all files in the routes directory and then calling them as a function. So if any of those files do not follow the general pattern below you'll get the error you're seeing:
module.exports = function(app, models) {
// Add this file's routes using app.get, etc. calls.
...
};
The error reports that the value of require('./routes/' + routeName) is not a function. So you have only one real possible source of the problem.
If './routes/'+routeName doesn't exist, node should throw an error (in v0.8.16 at least), so that isn't it. So the most obvious one is that the module being loaded doesn't export a function (as the error suggests).
You should run console.log('routeName: ', routeName) right before the require statement that is on line 60 of app.js and try running it again. Then, after finding the value of routeName, look in the file it's trying to open. Odds are either module.exports is either exporting an object (or an array, string etc), or is not set at all.
If you're adding routes in the routes folder, take care to follow the same exporting style as the author, namely module.exports = function(app, models) {...}