Express.js : express() not a function error - javascript

I'm learning express and running the code from the terminal gives me errors, below are my code and the terminal error prompt
const express = require("express");
const app = express();
app.listen(3000);
Terminal said:
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and 'C:\Users\ENIOLA YUSUFF\desktop\my-express-server\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///C:/Users/ENIOLA%20YUSUFF/desktop/my-express-server/server.js:5:17
←[90m at ModuleJob.run (node:internal/modules/esm/module_job:197:25)←[39m
at async Promise.all (index 0)
←[90m at async ESMLoader.import (node:internal/modules/esm/loader:337:24)←[39m
←[90m at async loadESM (node:internal/process/esm_loader:88:5)←[39m
←[90m at async handleMainPromise (node:internal/modules/run_main:61:12)←[39m
I tried using this code beneath instead thinking it was the difference in the node version but it solved half the problem.
import * as express from "express";
const app = express();
app.listen(3000);
Terminal error:
$ node server.js
file:///C:/Users/ENIOLA%20YUSUFF/desktop/my-express-server/server.js:2
const app = express();
^
TypeError: express is not a function
at file:///C:/Users/ENIOLA%20YUSUFF/desktop/my-express-server/server.js:2:13
at ModuleJob.run (node:internal/modules/esm/module_job:197:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:337:24)
at async loadESM (node:internal/process/esm_loader:88:5)
at async handleMainPromise (node:internal/modules/run_main:61:12)

You probably have "type": "module" in the file. That's why you have to use import instead of require.
You should be able to use import express from "express" for it to work.

Try this:
import express from 'express';
const app = express();

Related

NWJS - A dynamic link library (DLL) initialization routine failed

I'm tryin to build an app which requires sqlite3 Modul.
My app works fine when I run it from cmd node server.js
but when I run it from NWJS crashes and throws the error below
Uncaught Error: A dynamic link library (DLL) initialization routine failed.
\\?\C:\Users\Coder Bilall\Desktop\My Work\NWJS\GMoney\Gmoney\node_modules\sqlite3\lib\binding\napi-v3-win32-x64\node_sqlite3.node
at Object.Module._extensions..node (node:internal/modules/cjs/loader:1206:18)
at Module.load (node:internal/modules/cjs/loader:991:32)
at Function.Module._load (node:internal/modules/cjs/loader:831:14)
at Module.require (node:internal/modules/cjs/loader:1015:19)
at require (node:internal/modules/cjs/helpers:92:18)
at Object.<anonymous> (C:\Users\Coder Bilall\Desktop\My Work\NWJS\GMoney\Gmoney\node_modules\sqlite3\lib\sqlite3-binding.js:4:15)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1161:10)
at Module.load (node:internal/modules/cjs/loader:991:32)
at Function.Module._load (node:internal/modules/cjs/loader:831:14)
My server.js Code
const express = require('express')
const sqlite3 = require('sqlite3').verbose();
const LocalStorage = require('node-localstorage').LocalStorage;
let exec = require('child_process').exec, child;
const connectionTester = require('connection-tester');
const notifier = require('node-notifier');
const path = require('path');
const fs = require('fs');
const os = require('os');
const readline = require('readline');
const {google} = require('googleapis');
const ToCsv = require("sqlite-to-csv");
var cookieParser = require('cookie-parser')
const mailjet = require ('node-mailjet')
.connect('878dcf9b5a0ae7cf07498b6ab3d73ca7', 'c6c90ff0878e2b9640a6c342f84e142e')
const db = new sqlite3.Database('mydb.db');
const application = express();
application.use(cookieParser());
const port = 2020;
application.get('/', (req, res) => {
res.send('Hello World');
});
application.listen(port, () => {
console.log(`Example application listening at http://localhost:${port}`)
})
Please Help me 🥺🥺🥺🥺
The code failing is referencing a node binding sqlite3\lib\binding\napi-v3-win32-x64.
When you npm install some node modules will download or build files unique to your operating system (win32, linux, darwin), your architecture (x86, x64), and your Node.js ABI Version (47, 72, 88). If your globally installed version of Node is not the same as the version built in to NW.js, your module will be incompatible.
Try this:
Delete your node_modules and package-lock.json
Change your Node.js version to be the same as what is built in to that version of NW.js
Then do an npm install and see if it works
This may not be your issue, but it may resolve other issues and is quick to test.
What version of Node.js is in NW.js?
https://nwjs.io/versions.json
How do I switch Node.js versions globally?
Uninstall Node.js completely.
Install a Node Version Manager (nvm):
Linux/OSX: https://github.com/nvm-sh/nvm
Windows: https://github.com/coreybutler/nvm-windows
Windows alternative: https://github.com/marcelklehr/nodist
Consult the docs for the version of nvm you installed. Use it to install and switch to the correct Node.js version
You may also want to look at this NW.js wiki page:
https://github.com/nwjs/nw.js/wiki/Save-persistent-data-in-app#sqlite3

ReferenceError: require is not defined MongoDB

I'm trying to connect to my MongoDB database and I'm getting this error
ReferenceError: require is not defined
at file:///Users/admin/mjml/mjml/playground.js:1:21
at ModuleJob.run (node:internal/modules/esm/module_job:146:23)
at async Loader.import (node:internal/modules/esm/loader:165:24)
at async Object.loadESM (node:internal/process/esm_loader:68:5)
const MongoClient = require('mongodb').MongoClient
const uri =
'------------------------------'
const client = new MongoClient(uri, { useNewUrlParser: true })
client.connect((err) => {
const collection = client.db('test').collection('devices')
// perform actions on the collection object
client.close()
})
You are attempting to use require() inside an ESM module (you can see the Object.loadESM in the call stack of the error) which tells us it's an ESM module. You can't use require() in that type of module. Instead, you must use import.
So, you probably want:
import {MongoClient} from "mongodb";

How can I use Dialogflow-fulfillment library while utilizing the serverless architecture?

I'm setting up a lambda function using serverless that will be invoked through a Webhook in Google's NLP Dialogflow. My end goal is to be able to use the dialogflow-fulfillment library.
I have tried reinstalling node_modules by doing "npm install ..." to all the required modules. The package.json has all dependencies require.. using npm init.
// handler.js
const debug = require('debug')('http');
const express = require('express')
const sls = require('serverless-http');
const app = express();
app.get('/', async (req, res, next) => {
//console.log(req + res);
const { WebhookClient } = require('dialogflow-fulfillment')
const agent = new WebhookClient({ req, res });
function justSayHi(agent) {
console.log(`Something's happening`);
agent.add('Hello from dialogflow-fulfillment');
}
let intentMap = new Map();
intentMap.set('justsayhi', justSayHi);
agent.handleRequest(intentMap);
console.log("webhook called")
});
module.exports.server = sls(app);
When printing the logs in the command prompt sls logs -f app, I get the following error message:
"Unable to import module 'app': Error
at Function.Module._resolveFilename (module.js:547:15)
at Function.Module._load (module.js:474:25)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)"
Again, my end goal is to be able to use Dialogflow-fulfillment library utilizing the serverless architecture.
I'm wondering why it's saying unable to import module app.
I'm open to restructuring how I have this set up also, I have not found a good way to do this so far.

mongoose.connect(), first argument should be String, received undefined

I am trying to set the test database for the testing purpose, but its not working.
I am trying to connect to MongoDB using mongoose, but finding problem in the connection error shows:
throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
^
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()`is a string.
at new MongooseError (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mongoose/lib/error/mongooseError.js:11:11)
at NativeConnection.Connection.openUri (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mongoose/lib/connection.js:424:11)
at Mongoose.connect (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mongoose/lib/index.js:230:15)
at Object.<anonymous> (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/server/db/mongoose.js:5:10)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/server/models/Todo.js:1:82)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/server/tests/server.test.js:4:16)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
at /media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mocha/lib/mocha.js:250:27
at Array.forEach (<anonymous>)
at Mocha.loadFiles (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mocha/lib/mocha.js:247:14)
at Mocha.run (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mocha/lib/mocha.js:576:10)
at Object.<anonymous> (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mocha/bin/_mocha:637:18)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
error Command failed with exit code 1.
I am passing a valid String, but Its not working!
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI, err => {
if(err)
console.log(err);
}
);
module.exports = {
mongoose
};
Here is the Script to run mocha:
export NODE_ENV='test' && mocha server/**/*.test.js
Here is the configuration code:
const config = require('./config.json');
const env = process.env.NODE_ENV.toString() || 'development';
if(env === 'test' || env === 'development') {
const envConfig = config[env];
Object.keys(envConfig).forEach(key => {
process.env[key] = envConfig[key];
});
};
console.log(env);
Here is the config.json file:
{
"test": {
"PORT": 3000,
"MONGODB_URI": "mongodb://localhost:27017/TodoTest"
},
"development": {
"PORT": 3000,
"MONGODB_URI": "mongodb://localhost:27017/Todo"
}
}
Thanks for the help!
I think you miss importing env file.
require('dotenv').config({ path: 'ENV_FILENAME' });
To read from .env file you have to install dotenv ( npm i dotenv / yarn add dotenv)
and then just add this on top of your file.
const dotenv = require("dotenv");
dotenv.config();
I was also facing same problem after add code { useNewUrlParser: true } in mongoose.connect() method. Problem resolved.
mongoose.connect(config.DB,{ useNewUrlParser: true }));
In the server directory,
npm install dotenv
In your server.js:
If you use "type":"module" in your package.json file then,
import dotenv from 'dotenv';
import mongoose from 'mongoose';
dotenv.config();
or,
const mongoose = require('mongoose')
require('dotenv').config()
Add a .env file in the server directory,
PORT=5000
MONGO_URL= yourURL
In the server.js,
const url = process.env.MONGO_URL
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log("Server up and running!")
.catch((error) => console.log(error.message)
mongoose.set('useFindAndModify', false)
i have encountered the same error, this thread didn't help... here's my solution it was simple! im using express, mongo, mongoose, and dotENV
file 1 === db.js
import mongoose from 'mongoose';
const connectDB = async ()=>{
try{
const conn = await mongoose.connect(process.env.MONGO_URI,{
//must add in order to not get any error masseges:
useUnifiedTopology:true,
useNewUrlParser: true,
useCreateIndex: true
})
console.log(`mongo database is connected!!! ${conn.connection.host} `)
}catch(error){
console.error(`Error: ${error} `)
process.exit(1) //passing 1 - will exit the proccess with error
}
}
export default connectDB
file 2= server.js
import express from 'express'
import dotenv from 'dotenv'
import connectDB from './config/db.js' // DB connection
import products from './data/products.js'
dotenv.config()
const PORT = process.env.PORT || 5000
const mode = process.env.NODE_ENV
const app = express()
connectDB() //this function connects us to the DB!!!
. . . more code…
> solution: the connectDB() expression must come after the dotenv.config() expression.
and that's it ! :)
Since error message returned UNDEFINED uri parameter, .toString() will NOT work.
You can use the String() function: String(your connection parameter).
Also, in if(env === 'test' || env === 'development') try not to use (===), it is a strict equality.
Instead try if(env == 'test' || env == 'development'). This is a loose equality. It doesn't care about the type match and will convert second operand's type to first one's type.
I ran into the same problem.
1. I saved my ATLAS_URI ID to a file called .env
2. My .env file was in the wrong directory, that's how the problem cause
3. Solution: I used "ls -a" command to make sure my .env file is in the same location as my server
try using this method worked for me.
mongoose.connect(`${process.env.MONGO_URL}`, {useNewUrlParser: true, useUnifiedTopology: true}, ()=>{
console.log("mongodb is connected")
});
there is a very small mistake Your .env file should exist in your project directory. maybe your .env file is placed in a different folder. check your .env file location
Please try the below steps
Step 1 - Install dotenv package
# with npm
npm install dotenv
# with Yarn
yarn add dotenv
Step 2 - Create a new env file e.g config.env
Step 3 - Write the below code in the config.env file
DATABASE = MONGO_URL
PORT = port_number
Step 4 - Write the below code in your main server file (in my case it is index.js)
const dotenv = require("dotenv"); //require dotenv package
dotenv.config({ path: "./config.env" }); //import config.env file
const DB = process.env.DATABASE;
const Port = process.env.PORT;
mongoose
.connect(DB, {
usenewurlparser: true,
useunifiedtopology: true,
})
.then(() => {
console.log("Successfully connected ");
})
.catch((error) => {
console.log(`can not connect to database, ${error}`);
});
This is what solved my problem. Happy Coding!
// Connect to MongoDB
mongoose.connect('mongodb://yourusername:yourpassword#ds121825.mlab.com:11025/yourmongodb', {useNewUrlParser: true});
mongoose.connection.once('open', function(){
console.log('Conection has been made!');
}).on('error', function(error){
console.log('Error is: ', error);
});
I had the same problem, but then I realized that I saved the .env file as .env.txt which caused the issue. I deleted the file and created another file without .txt at the end and everything worked find.
I hope this helps.
Dhiya Aljaradi
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
Always put useNewUrlParser:true before putting the useUnifiedTopology:true, and then the rest.
i have taken this error message, you have to declare .env file after installing dotenv package. if you declare file before installing package , variable will be undefined
If you are getting the same error, Even after configuring dotenv and setting everything step by step, then you have to restart your MongoDB and server and wait for some time.
Look at the images, I have done nothing, just restarted MongoDB, and the server
sometimes it's a mongo server issue
I had a similar issue, fixed by adding this code snippet.
mongoose.connect(config.DB,{ useMongoClient:true });
Make sure that you have the .env file with the constants that you are using defined.
I had same error, for me it was because I was trying to use environment variables in globalSetup which had the file for initiating db connection.. mongoose.connect(global.__MONGO_URI__
Apparently, environment variables are not initialised yet in globalSetup so I had to move the code somewhere else, either to setupFilesAfterEnv or by using Async Test Environment
const db = process.env.MONGO || 'test'
mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology:true,
useCreateIndex: true
}).then(()=>{
console.log("conected to mongodb");
}).catch(error => {
console.log("mongo error",error);
})
just change the env
const db = process.env.MONGO || 'test'
in case you've forgotten to import/require dotenv, then you can run dotenv before running your app using --require dotenv/config
node --require dotenv/config index.js // regular node command
// nodemon to restart application whenever a file gets changed
nodemon --require dotenv/config index.js
// integrate with babel-node if you're using latest JS features like import/export
nodemon --require dotenv/config index.js --exec babel-node
No need to require dotenv and call config function within codebase. Enjoy!
What I was doing wrong was I created js file to store the key:
module.export = {
MONGOURI : "Your Key"
}
and from my app.js I was fetching the key with different keyname like
const {MongoUri} = require('./keys')
after changing MongoUri to MONGOURI , it worked fine.
If we don't want to define the path of the .env file like this,
require('dotenv').config({ path: 'ENV_FILENAME' });
we can place .env file in the same place as our main file, which was App.js in my case. So we could directly write
require('dotenv').config()
I came across this same issue and here is my fix:
the process.env.MONGODB_URL should be in a string.
Check it out
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('process.env.MONGODB_URI', err => {
if(err)
console.log(err);
}
);
module.exports = {
mongoose
};
my .env file was named .dotenv by mistake.
after changing it to .env everything worked 👌
i had a similar issue, Make sure that you have the .env in "/" (next to your package.json file).if do not want to require and load dotenv in your application code or still have an issue run your server through:
node -r dotenv/config your_script.js.
otherwise, if your file containing environment variables is located elsewhere, you have to use path module:
common js: require('dotenv').config({ path: '/custom/path/to/.env' })
ES:dotenv.config({ path: '/custom/path/to/.env' })
after using
require("dotenv").config(); or import dotenv from "dotenv";
dotenv.config(); put your .env file in the same folder as server file
You can check for the ".env" file in your folder has the exact name, else it won't work.
If you have named the ".env" file something else then please change it.
I have faced the same problem. I solved it easily.
Step 1: npm install dotenv
Step 2: require('dotenv').config()
Step 3: Create a .env file
Step 4: Push Into this code dot env (.env) file DB_USER = ******** and DB_PASS = ********
Step 5:
const dbURL = mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}#techbd71.5ewxj.mongodb.net/enter
table name here?retryWrites=true&w=majority
mongoose.connect(dbURL, {useNewUrlParser: true, useUnifiedTopology: true})
.then(()=>console.log('DB Ok'))
.catch(err => console.log(err))
I also got stuck with same problem so I fixed it like this..
mongoose.connect('mongodb+srv://username:password#cluster0.h9zpqsi.mongodb.net/?retryWrites=true&w=majority',{
useNewUrlParser:true,})
// Using MONGO_URI instead of using process.env.MONGO_URI

Mongoose.connect not working

When I run node server.js in the command line I get this error:
C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms>node server.js
C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\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 (C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\node_modules\express\lib\router\index.js:458:13)
at Function.<anonymous> (C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\node_modules\express\lib\application.js:220:21)
at Array.forEach (<anonymous>)
at Function.use (C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\node_modules\express\lib\application.js:217:7)
at Object.<anonymous> (C:\Users\Shaelyn\WebstormProjects\CIT366Projects\cms\server.js:34:5)
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)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
I think part of it might be that the mongoose.connect is an unresolved function. Does anyone know how to fix this error?
This is my code:
// Get dependencies
var express = require('express');
var path = require('path');
var http = require('http');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
// import the routing file to handle the default (index) route
var index = require('./server/routes/app');
const messageRoutes = require('./server/routes/messages');
const contactRoutes = require('./server/routes/contacts');
const documentRoutes = require('./server/routes/documents');
// establish a connection to the mongo database
mongoose.connect('mongodb://localhost:27017/cms');
var app = express(); // create an instance of express
// Tell express to use the following parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(logger('dev')); // Tell express to use the Morgan logger
// Tell express to use the specified director as the
// root directory for your web site
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/', index);
app.use('/messages', messageRoutes);
app.use('/contacts', contactRoutes);
app.use('/documents', documentRoutes);
// Define the port address and tell express to use this port
const port = process.env.PORT || '3000';
app.set('port', port);
// Create HTTP server.
const server = http.createServer(app);
// Tell the server to start listening on the provided port
server.listen(port, function() {console.log("API running on localhost: " +
port)});
Your mongoose.connect call is working fine. If it wasn't then you would definitely have received a PromiseRejection for connection failure and a deprecated warning for UnhandledPromiseRejection.
Still you can ensure that by adding few event listeners on mongoose events.
mongoose.connect('mongodb://127.0.0.1:27017');
mongoose.connection.on('connected', () => console.log('Connected'));
mongoose.connection.on('error', () => console.log('Connection failed with - ',err));
Coming to your error. This is more likely to happen when you have passed anything but a function as your handler to your app.use or router.use call. app.use and router.use both require functions to be passed to them which later express would call whenever a request arrives.
The import statements on top of your code, where you require your routers are most likely to be the culprits here as by default every module.exports is an object.
I need to look into your router files to further dig into the problem, but you may yourself verify the same. Just see if the module.exports of every router file imported points to a express router instance - express.Router(). This way every route file will export a configured express.Router() instance which will be a function attached to app via app.use() call.
Replace mongodb://localhost:27017 with mongodb://127.0.0.1:27017
To capture the exact error please follow the below approach.
const mongoose = require('mongoose');
const url = "mongodb://127.0.0.1:27017";
mongoose.connect(url).then(() => {
console.log("Connected to Database");
}).catch((err) => {
console.log("Not Connected to Database ERROR! ", err);
});

Categories