celsomtrindade
celsomtrindade

Reputation: 4671

AngularJs ReferenceError: require is not defined

I know there is other questions about this problem, but I've ready more than 10 answers and tried every single one and none of them worked for me.

I'm getting this error: Uncaught ReferenceError: require is not defined when i try to load an external plain javascript file to encode in JWT.

This is the file I'm trying to include with require(): https://github.com/hokaccha/node-jwt-simple I've download with npm.

In my code I tried lots of things.

With all of those attempts, I got the same errors. What am I doing wrong?

This is the code I'm using right now:

index.html

<head>
<script type="text/javascript" src="dist/js/angular.min.js"></script>
<script type="text/javascript" src="dist/js/ui-router.min.js"></script>
<script type="text/javascript" src="dist/js/jwt.js"></script>
[... rest of head ...]

appCtrl.js (will concat later on the build with the rest of the app)

.controller('MainCtrl', 
    ['$rootScope', '$scope', '$state', 
    function($rootScope, $scope, $state) {
        var jwt = require('jwt');
        var payload = { foo: 'bar' };
        var secret = 'xxx';
        var token = jwt.encode(payload, secret);
        console.log(token);
}])

My main objective with this is to handle the user authentication based on a JWT token. The problem right now is to encode/decode the token when the user is login in into the app.

Even with all of these, I still get the error. Do you guys know how to fix this?

Upvotes: 4

Views: 17065

Answers (2)

Josh Beam
Josh Beam

Reputation: 19772

If you want to use require on the client, you need to use something like Browserify or webpack (I definitely recommend the latter).

You're getting that error because, in fact, you have never defined require anywhere on your client-side code. That JWT repo does not provide that functionality for you.

Also, looking at the docs for the JWT repo you provided, it appears that it expects you to use it in a node.js environment (which provides the commonjs require for you).

Upvotes: 5

Paul G
Paul G

Reputation: 847

On the server side (ie server.js file), for node, use:

var jwt = require('jwt-simple');

Then, to encode:

var secret = "Ieaticecreamforbreakfast";

and in your login functionality... once you check the login criteria

var token = jwt.encode({id: ID, otherInfo: "can go here"}, secret); 

res.send({token: token});

You can then set the response token in as a header for additional http requests in your angular, frontend side. Therefore, whenever a user makes a request to the backend, you have access to their encoded ID in the JWT

Upvotes: 0

Related Questions