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');
Related
I have a basic nestjs app, I'm trying to use winston as logger service... this breaks my app and I really don't know to fix/revert this.
I've tried uninstalling the winston packages, rm node_modules and npm install again, nothing is working.
node -v: v11.15.
nest -v: 7.1.5
yarn -v: 1.22.4
npm -v: 6.14.5
The error I get:
[11:37:19 AM] Found 0 errors. Watching for file changes.
internal/modules/cjs/loader.js:670
throw err;
^
Error: Cannot find module './app.module'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:668:15)
at Function.Module._load (internal/modules/cjs/loader.js:591:27)
at Module.require (internal/modules/cjs/loader.js:723:19)
at require (internal/modules/cjs/helpers.js:14:16)
at Object.<anonymous> (/Users/dtmirror/app-api/dist/src/main.js:4:22)
at Module._compile (internal/modules/cjs/loader.js:816:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
at Module.load (internal/modules/cjs/loader.js:685:32)
at Function.Module._load (internal/modules/cjs/loader.js:620:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)
package installed:
npm i winston
LoggerService:
import * as winston from 'winston';
import { LoggerOptions } from 'winston';
export class LoggerService {
private logger;
public static loggerOptions: LoggerOptions = {
transports: [
new winston.transports.File({ filename: 'app.log' })
]
}
constructor(private context: string, transport?) {
this.logger = (winston as any).createLogger(LoggerService.loggerOptions);
}
log(message: string): void {
const currentDate = new Date();
this.logger.info(message, {
timestamp: currentDate.toISOString(),
context: this.context,
})
}
}
main.ts:
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import { LoggerService } from '../logger.service'; // <-- this breaks everything
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
The moment I run yarn start:dev in this stage everything breaks...
Seems like a bad import for the AppModule. According to comments, logger was outside the src directory, which ends up causing the dist to take on a different shape
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 had a perfectly working relay modern app with 1.1.0 babel-plugin-relay + react-relay + react-compiler + graphql 0.10.x, react 15.5.x but since upgrading all of them to 1.4.1 and graphql to 0.11.7 and react to 16.0.0 I keep getting this error when running npm start:
ERROR in ./src/main.js
Module build failed: Error: BabelPluginRelay: Expected plugin context to include "types", but got:[object Object]
at BabelPluginRelay (/Users/johndoe/testing/atc/node_modules/babel-plugin-relay/lib/BabelPluginRelay.js:36:11)
at Object.<anonymous> (/Users/johndoe/testing/atc/src/babelRelayPlugin.js:28:18)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at /Users/johndoe/testing/atc/node_modules/babel-core/lib/transformation/file/options/option-manager.js:178:20
# multi (webpack)-dev-server/client?http://localhost:3333 ./src/main.js
webpack: Failed to compile.
with babel-plugin-relay like so:
babelRelayPlugin.js:
const babelRelayPlugin = require('babel-plugin-relay')
const { introspectionQuery, buildClientSchema, printSchema } = require('graphql/utilities')
const request = require('sync-request')
const fs = require('fs')
const path = require('path')
const schemaPath = path.join(__dirname, 'schema');
const graphqlHubUrl = 'https://myhub.com/dev/graphql'
const response = request('POST', graphqlHubUrl, {
qs: {
query: introspectionQuery
}
})
console.log('response ', response)
const schema = JSON.parse(response.body.toString('utf-8'))
console.log('schema ', schema)
const graphQLSchema = buildClientSchema(schema.data);
fs.writeFileSync(
`${schemaPath}.graphql`,
printSchema(graphQLSchema)
);
module.exports = babelRelayPlugin(schema.data, {
abortOnError: true
})
and webpack.config.js:
query: {
presets: ['env', 'react', 'stage-2'],
plugins: ['relay', 'transform-class-properties', __dirname + '/src/babelRelayPlugin']
}
the question is why ? and how I can fix it? because in the response I can clearly see types:
Solved it.
Had to change this:
module.exports = babelRelayPlugin(schema.data, {
abortOnError: true
})
to this:
module.exports = babelRelayPlugin(schema.data.__schema, {
abortOnError: true
})
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);
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 = {}