I have entities directory that store user.js file like this:
"use strict";
class User {}
module.exports = User;
and in my index.js:
var User = require("./entities/User")
but I got an error
Error: Cannot find module './entities/User'
at Function.Module._resolveFilename (module.js:470:15)
at Function.Module._load (module.js:418:25)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Socket.socket.on (/home/etours/capstone-etours/index.js:154:21)
at emitTwo (events.js:106:13)
at Socket.emit (events.js:194:7)
at /home/etours/capstone-etours/node_modules/socket.io/lib/socket.js:503:12
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
The require function it's case sensitive so you have to write the path exactly how you created.
if you use the U lowercase it's gonna work :D
You should try this code:
user.js
var User = function() {};
module.exports = User;
var User = class User {
};
module.exports.User = User;
index.js
var User = require("./user");
console.log(User);
You can also try below code:
user.js:
var User={};
module.exports = User;
var User = class User {
};
module.exports.User = User;
index.js:
var User = require("./user");
console.log(User);
Related
I can't access this module I'm exporting. I have no clue what's wrong.
I'm trying to export a database connection so it's available everywhere.
database.js
import { Sequelize } from 'sequelize';
var server = 'aggregatesqlserver.database.windows.net'
var database = 'AGGREGATEDEVDB'
var username = '****'
var password = '****'
var driver= '{ODBC Driver 17 for SQL Server}'
const sequelize = new Sequelize(database, username, password, {
host: server,
dialect: "mssql"
});
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
module.exports = sequelize;
When I try to access if from this script
main.ts
import { NestFactory } from '#nestjs/core';
import { NestExpressApplication } from '#nestjs/platform-express';
import { join } from 'path';
import { AppModule } from './app.module';
import { createConnection, Connection} from "typeorm";
const db = require('./config/database');
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
);
app.useStaticAssets(join(__dirname, '..', 'public'));
app.setBaseViewsDir(join(__dirname, '..', 'views'));
app.setViewEngine('hbs');
const [results, metadata] = await db.query("UPDATE [dbo].[storedProc] SET someData = RAND() WHERE columnID = 1");
await app.listen(3000);
}
bootstrap();
It gives me this error no matter what...
Error: Cannot find module './config/database'
Require stack:
- /Users/paytondugas/Desktop/RapidTek/nest/SQL/csp_copy/dist/main.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:885:15)
at Function.Module._load (internal/modules/cjs/loader.js:730:27)
at Module.require (internal/modules/cjs/loader.js:957:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (/Users/paytondugas/Desktop/RapidTek/nest/SQL/csp_copy/src/main.ts:7:12)
at Module._compile (internal/modules/cjs/loader.js:1068:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:933:32)
at Function.Module._load (internal/modules/cjs/loader.js:774:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
Here's the file system
Any clue on the problem...?
This behavior happens because you try to import a Javascript file from Typescript file. You can try:
1.
import * as db from './config/database';
Add this characteristic to allow JS modules import in tsconfig.json or your tsconfig
{
"compilerOptions": {
"allowJs": true
}
}
Sometimes such conflicts happen due to using ES5 module syntax instead of ES6 module syntax.
To avoid such problem try using only one module syntax, either the es5 or the es6
Try using
import db from './config/database';
instead of
const db = require('./config/database');
I'm getting this error when I update my server on nodemon.
C:\Users\mikae\Desktop\Project\node-express-swig-mongo\node_modules\mongoose\lib\index.js:523
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "superheros".
Use mongoose.model(name, schema)
at Mongoose.model (C:\Users\mikae\Desktop\Project\node-express-swig-mongo\node_modules\mongoose\lib\index.js:523:13)
at Object.<anonymous> (C:\Users\mikae\Desktop\Project\node-express-swig-mongo\routes\api.js:4:26)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
at Module.load (internal/modules/cjs/loader.js:879:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:903:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (C:\Users\mikae\Desktop\Project\node-express-swig-mongo\app.js:6:11)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
at Module.load (internal/modules/cjs/loader.js:879:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Module.require (internal/modules/cjs/loader.js:903:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (C:\Users\mikae\Desktop\Project\node-express-swig-mongo\bin\www:7:11)
[nodemon] app crashed - waiting for file changes before starting...
api.js
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Superhero = mongoose.model('superheros');
router.get('/superheros', function(req, res) {
Superhero.find(function(err, superheros){
console.log(superheros)
res.render(
'api',
{title : 'Superhero API', superheros : superheros}
);
});
});
router.post('/superheros', function(req, res) {
console.log(req.body.name);
res.redirect('/api/superheros');
});
module.exports = router;
database.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Superhero = new Schema(
{name : String}
);
mongoose.model('superheros', Superhero);
mongoose.connect('mongodb://localhost/node-superhero');
I'm building Crud with Mongoose, Node, and Express. This error appears when I write method POST on api.js and even erasing error remains. I'm learning from this tutorial
https://mherman.org/blog/node-express-swig-mongo-primer/
The short answer to your question is that you are not exporting the Schema in database.js
You should do:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var superheroSchema = new Schema(
{name : String}
);
module.exports = mongoose.model('Superhero', superheroSchema);
Also it is better to seprate the connection to the database in a different file or atleast use it in your main file like this:
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true })
.then(//Some code here...)
.catch(error => handleError(error));
It is simply wrong to try and make a connection to the database inside a model definition.
And when requiring the schema use:
var Superhero = require('{path to the file containing the schema}')
I am creating an API, so I want to add a user system and validate access to the API.
This would be the middleware for validation:
'use strict'
const jwt = require('jwt-simple');
const moment = require('moment');
const config = require('../settings/config');
function isAuth(req, res, next) {
if (!req.headers.authotization) {
return res.status(403).send({
message: `No tiene autorizacion`
})
}
const token = req.headers.authotization.split(" ")[1];
const payload = jwt.decode(token, user, config.token.secret_token);
if (payload.exp <= moment().unix()) {
return res.status(401).send({
message: 'El token ha expirado'
})
req.user = payload.sub;
next();
}
}
module.exports = isAuth;
while this would be the route:
'use strict'
const express = require('express');
const router = express.Router();
const auth = require('../middlewares/auth');
router.get('/', auth.isAuth, (req, res) => {
res.status(200).send({
message: `Tienes acceso`
})
})
on the other hand, this is my main application settings (app.js):
const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const app = express();
const config = require('./config')
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
// Routes variables
const productRouter = require('../routes/product');
const privateRouter = require('../routes/private');
// Routes uses
app.use('/api/product', productRouter);
app.use('/private', privateRouter);
app.listen(config.app.port, err => {
if (err) throw err;
console.log(`Server listening on port ${config.app.port}`)
})
module.exports = app;
I am getting this error:
D:\api-rest-carlos-azaustre\node_modules\express\lib\router\route.js:202
throw new Error(msg);
^
Error: Route.get() requires a callback function but got a [object
Undefined]
at Route. [as get] (D:\api-rest-carlos-azaustre\node_modules\express\lib\router\route.js:202:15)
at Function.proto. [as get] (D:\api-rest-carlos-azaustre\node_modules\express\lib\router\index.js:510:19)
at Object. (D:\api-rest-carlos-azaustre\routes\private.js:6:8)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object. (D:\api-rest-carlos-azaustre\settings\app.js:15:23)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18) [nodemon] app crashed - waiting for file changes before starting...
And sometimes this line is added at the top of error:
(node:3092) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 exit listeners > added to [Bus]. Use emitter.setMaxListeners() to increase limit
After reading the answers, I edit my question. I have placed only auth and not auth.isAuth and I am getting the following error:
D:\api-rest-carlos-azaustre\node_modules\express\lib\router\index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a
Object
at Function.use (D:\api-rest-carlos-azaustre\node_modules\express\lib\router\index.js:458:13)
at Function. (D:\api-rest-carlos-azaustre\node_modules\express\lib\application.js:220:21)
at Array.forEach ()
at Function.use (D:\api-rest-carlos-azaustre\node_modules\express\lib\application.js:217:7)
at Object. (D:\api-rest-carlos-azaustre\settings\app.js:20:5)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object. (D:\api-rest-carlos-azaustre\index.js:3:13)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14) [nodemon] app crashed - waiting for file changes before starting...
Does anybody know what is it due to?
module.exports = isAuth; means you're only exporting the function and nothing else. That means when you do const auth = require('../middlewares/auth');, auth is the actual function, not an object containing isAuth as a property.
So, doing router.get('/', auth, (req, res) => { should work, instead of auth.isAuth which is invalid.
Learn more about modules here: https://js.evie.dev/modules
Yes, you export the function with this code: module.exports = isAuth;
But then you call use it like this: auth.isAuth
Assuming you're doing something like const auth = require('./bin/auth.js'); or whatever
auth would be the function itself -- there will be no isAuth property.
So you should try this:
router.get('/', auth, (req, res) => {
You haven't posted your entire code, so this is just a best guess.
I've made a basic node.js application including a controller and a service. I keep getting this error when i try to run the application. It should be a get method for returning any table based on the passed 'namespace' and 'table' parameters.
Controller:
var express = require('express');
const testService = require ('../services/testService');
const getAnyController = async(req, res, next) => {
var table = req.params.table;
var namespace = req.params.namespace;
table = table.toUpperCase();
namespace = namespace.toLowerCase();
var client = req.db;
try{
var serviceResponse = await testService.GetAny(table, namespace, client);
res.status(200).send(serviceResponse);
next();
}
catch(error){
console.log(error.message);
res.status(500) && next(error);
}
}
module.exports = {
getAnyController
}
Service:
var express = require('express');
function GetAny(table, namespace, client) {
var getScript = 'SELECT * from ' + namespace + '.' + table;
client.query(getScript, (err, response) => {
if(err) {
return 'Error: ' + err.toString();
}
return response;
});
}
module.exports = {
GetAny
};
Index.js:
const express = require("express");
const router = express.Router();
const testController = require('../controllers/testController');
router.get("/test/:namespace/:table", (req, res) => {
testController.getAnyController(req, res);
});
module.exports = router;
This is the error I'm getting:
/home/vcap/app/node_modules/express/lib/router/index.js:635
return fn.apply(this, arguments);
^
TypeError: Cannot read property 'apply' of undefined
at /home/vcap/app/node_modules/express/lib/router/index.js:635:15
at next (/home/vcap/app/node_modules/express/lib/router/index.js:210:14)
at Function.handle (/home/vcap/app/node_modules/express/lib/router/index.js:174:3)
at router (/home/vcap/app/node_modules/express/lib/router/index.js:47:12)
at Object.<anonymous> (/home/vcap/app/server.js:46:33)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
npm
ERR! code ELIFECYCLE
npm ERR!
errno 1
npm ERR! js#1.0.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the js#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
Found the error. The router was not defined in server.js
I am following a tutorial on how to set up a basic mvc in Nodejs using the hapi server and a few other packages.
Tutorial: https://www.sitepoint.com/node-js-mvc-application/
Git for my project: https://github.com/christoph88/node-js-mvc-tut/
I have an error when I try to launch the server:
~/Projects/node-js-mvc-tut$ node server.js
/home/christoph/Projects/node-js-mvc-tut/server.js:33
Models.sequelize.sync().then(() => {
^
TypeError: Cannot read property 'sync' of undefined
at Object.<anonymous> (/home/christoph/Projects/node-js-mvc-tut/server.js:33:17)
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)
at Function.Module.runMain (module.js:605:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:575:3
Model is defined within the requirements. I do not understand why sync is undefined. Sequelise is required within the lib/index.js file.
'use strict';
const Hapi = require('hapi');
const Hoek = require('hoek');
const Path = require('path');
const Settings = require('./settings');
const Routes = require('./lib/routes');
const Models = require('./lib/models/');
const server = new Hapi.Server();
server.connection({ port: Settings.port });
server.register([
require('vision'),
require('inert')
], (err) => {
Hoek.assert(!err, err);
server.views({
engines: { pug: require('pug') },
path: Path.join(__dirname, 'lib/views'),
compileOptions: {
pretty: false
},
isCached: Settings.env === 'production'
});
// Add routes
server.route(Routes);
});
Models.sequelize.sync().then(() => {
server.start((err) => {
Hoek.assert(!err, err);
console.log(`Server running at: ${server.info.uri}`);
});
});
Can somebody help me with this? Would be great to get this running so I can try to adapt it to my needs.
I have got it working by moving my index.js file to the models folder.
This file has the necessairy scripts that dispatches sequelise in the model thus fixing the problem.
Make sure you have exported the db in index.js
module.exports = db
and declared a db variable at the beginning of the file
var db = {}