Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB not saving data because "Uncaught ReferenceError: require is not defined"

I'm testing NodeJS and MongoDB. So, I've created an html file with a form.

That form grabs the user input and tries to save it to a Mongo database.

I've tried manually inserting the values into mongo using the console and it works.

I've started node server writing down node at the terminal, inside my EC2 amazon web server. I've already installed both (node and mongo).

The form looks like this:

<form>
<input type="email" name="email" class="form-control" id="email">
<input type="submit" onclick="avisoPago.insertarDB()" class="btn btn-danger" value="Avisar del pago ahora"></input>

And here's what I'm trying to do in the js file:

"use strict";
const mongojs = require("mongojs");
//string connection
const db = mongojs("localhost:27017/pagosDB",["pagosDB"]);

var avisoPago = {
    email: function () {    return $('#email').val();   },    
    insertarDB: function(){
            db.pagos.insert({
                email:"[email protected]",
                //I've also tried email:"this.email()",
                estado: "pendiente"
            });
    }

}

I've also installed mongojs (using npm install mongojs).

But I get this error avisos-de-pago.js:4 Uncaught ReferenceError: require is not defined

Note: Line 4 of the JS file is: const mongojs = require("mongojs");)

I know thata there is something very silly that I'm missing here...

like image 959
Rosamunda Avatar asked Mar 22 '26 06:03

Rosamunda


1 Answers

NodeJS is a server-side technology, not a client-side technology. In this case, NodeJS calls, like require(), do not work in the browser.

See browserify or webpack if you wish to serve browser-specific modules from NodeJS.

like image 184
Jordan Plamondon Avatar answered Mar 24 '26 19:03

Jordan Plamondon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!