I'm creating an Express.js API on a Node.js server. The API is used to access data stored on the server. I also keep a log of who's accessing the API in a database.
I'm trying to create an admin section that will use Angular.js to display the admin access logs neatly. I used the Angular Express Bootstrap seed to start my project:
https://github.com/jimakker/angular-express-bootstrap-seed/
My problem is that I need the controllers.js to access node modules but it doesn't seem to know that node exists. Here is my error:
controller.js
var mongo = require('mongodb');
[Uncaught ReferenceError: require is not defined]
How can I use node modules in Angular.js files?
The uncaught ReferenceError: required is not defined in JavaScript error usually occurs when JavaScript doesn’t know how to handle the require () function. The require () function is not supported by browsers by default.
Uncaught ReferenceError: require is not defined This usually happens because your JavaScript environment doesn’t understand how to handle the require () function reference. The require () function is only available by default on Node.js environment.
This means your code is running without any problem. Well, this was all about the function require () and the error related to it. If you stuck into any kind of error, don’t forget to google it and try to debug it on your own. This will teach you how to debug on your own as someone might have faced a similar problem earlier.
That is a specific feature of node.js, not of a browser. So, when you try to have the browser run your script, it does not have require (). There are ways to run some forms of node.js code in a browser (but not all). For example, you can get browser substitutes for require () that work similarly (though not identically).
Node is a server side technology, you would not typically use your node modules on the browser with Angular.js. However, if you want commonjs require functionality in the browser see: https://github.com/substack/node-browserify.
Ofcourse, a browser can't talk to mongodb directly which is why you need an API in the first place, angular would communicate with your API using HTTP.
Angular.js makes an $http call to Node.js which requires and talks to the mongodb.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With