Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js + Angular = Uncaught ReferenceError: require is not defined

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?

like image 425
RachelD Avatar asked Aug 12 '13 20:08

RachelD


People also ask

What is uncaught ReferenceError required is not defined in JavaScript?

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.

Why is require not defined in Node JS?

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.

What is require () error in JavaScript?

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.

Why can't I run a Node JS script in a browser?

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).


1 Answers

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.

like image 125
Merrick Christensen Avatar answered Oct 24 '22 07:10

Merrick Christensen