Why I get "Uncaught ReferenceError: require is not defined"? - javascript

I want to use lolapi, so I went with my terminal to folder where project is and did npm install lolapi.
My code is a really simple cordova app:
HTML:
<body>
<div class="app">
<h1> Lol App</h1>
</div>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/lolJ.js"></script>
</body>
JavaScript (lolJ.js):
var options = {
useRedis: true,
hostname: '127.0.0.1',
port: 6379,
cacheTTL: 7200
};
var lolapi = require('lolapi')('***-***-***-***-***', 'euw', options);
lolapi.setRateLimit(10, 500);
var summonerName = 'Wickd';
lolapi.Summoner.getByName(summonerName, function (error, summoner) {
if (error) throw error;
/* summoner object
{ Wickd:
{
id: 71500,
name: 'Wickd',
profileIconId: 613,
summonerLevel: 30,
revisionDate: 1408199475000
}
} */
console.log(summoner);
console.log(summoner[summonerName]);
var summonerId = summoner[summonerName].id;
lolapi.Summoner.getRunes(summonerId, function (error, runes) {
if (error) throw error;
// do something with runes
})
});
I replaced Wickd with my lol username, but still nothing happens.
As you can see I'm really new to this, so please, any guide will be great
Thanks

The require syntax is what's referred to as CommonJS, the default way of how you load modules within Node.js environments.
In order to use the require syntax in a browser environment you'd need to use tools like Browserify which handles this for you by bundling your application together with your dependencies.

Related

How to create a custom module for Node-Red for use require statement of node and require npm modules inside flows

I need help to create a custom node to use the require estatement of nodeJs in node-red, according to the documentation three files are required in a common directory:
require
-required.js
-required.html
-package.json
the package.json content is:
{
"name": "node-red-contrib-require",
"node-red": {
"nodes": {
"require": "required.js"
}
}
}
the required.html content is:
<script type="text/javascript">
RED.nodes.registerType("require", {
category: "function",
color: "#a6bbcf",
defaults: {
name: { value: "" },
},
inputs: 1,
outputs: 1,
icon: "file.png",
label: function () {
return this.name || "require";
},
});
</script>
<script type="text/html" data-template-name="require">
<div class="form-row">
<label for="node-input-name"
><i class="fa fa-tag" aria-hidden="true"></i> Module</label
>
<input type="text" id="node-input-name" placeholder="Name" />
</div>
</script>
<script type="text/html" data-help-name="required">
<p>
A simple node that implements the require statement of nodeJs to message
payloads as required modules
</p>
</script>
I don't know how to implement the code for required.js file, in NodeJs is so easy than create a
required function like:
function required(moduleName) {
try {
return moduleName ? require(moduleName) : undefined;
} catch (error) {
// console.log(error);
//Node red error handle is this ok or need changes?
node.error("error: " + error.toString(), undefined);
}
}
thanks for any help, at this point I don't know if this is possible or I'm looking for pink unicorns
Thanks to #knolleary
The solution is:
unsafe-function node for node-red node
unsafe-function node for node-red source
forked version of node-red See stackoverflow answer
You can require npm modules inside the javascript file of each node .
Your function should be this way to have the correct boolean value :
function required(moduleName) {
try {
require('https').get(`https://www.npmjs.com/package/${moduleName}`,function(response){
return response.statusCode == 200;
})
} catch (error) {
// console.log(error);
//Node red error handle is this ok or need changes?
node.error("error: " + error.toString(), undefined);
}
}

Log minified JavaScript errors in production code

I am running a back-end app with a React JS frontend on our intranet. I don't want to use services like Sentry or Rollbar to keep track of minified code in production because I don't want to upload our source-maps externally.
Are there any self-hosted solutions for tracking & logging errors in JS source-maps?
We are using a combination of JSNLog and Stacktrace. This is what goes into the <head> of your index.html:
<script src="~/js/jsnlog.min.js"></script>
<script src="~/js/stacktrace.min.js"></script>
<script src="~/js/stacktraceConfig.js"></script>
And below the contents of stacktraceConfig.js:
window.onerror = function (msg, file, line, col, error) {
var callback = function (stackframes) {
var stringifiedStack = stackframes.map(function (sf) {
return sf.toString();
}).join('\n');
JL('serverLog').fatalException({
msg: 'Exception! ' + stringifiedStack,
1: '--------------------------------------------------------------',
errorMsg: msg,
url: stackframes[0].fileName + ":" + stackframes[0].lineNumber,
functionName: stackframes[0].functionName,
lineNumber: stackframes[0].lineNumber,
column: stackframes[0].column,
x: '--------------------------------------------------------------',
}, error);
};
var errback = function (err) { console.log(err.message); };
StackTrace.fromError(error).then(callback).catch(errback);
// Tell browser to run its own error handler as well
return false;
};
You will have to configure JSNLog yourself to have it send the errors by mail.

Keycloak login returns 404 using JavaScript adapter

I'm using Keycloak's bower package to create a very basic demo HTML/JS app. I have Keycloak running locally and keycloak.init() seems to work (no error triggered). However when I call keycloak.login() a 404 is returned. Might the login URL be wrongly created by the adapter?
The URL returned by keycloak.createLoginUrl() is
https://<keycloak url>/realms/<realm>/protocol/openid-connect/auth?client_id=account&redirect_uri=file%3A%2F%2F%2FUsers%2Fjgallaso%2FProjects%2Fdemos%2Fkeycloak-simple-web-client%2Findex.html&state=b167dc0b-3e5b-4c67-87f7-fd5289fb7b8f&nonce=1e2cb386-51db-496a-8943-efcf4ef5d5e1&response_mode=fragment&response_type=code&scope=openid
And this is my entire code:
<head>
<script src="bower_components/keycloak/dist/keycloak.min.js"></script>
</head>
<body>
<button id="login">Login</button>
</body>
<script>
var keycloak = Keycloak({
url: 'https://keycloak-keycloak.192.168.37.1.nip.io',
realm: 'demo',
clientId: 'account'
});
keycloak.init()
.success(authenticated => {
document.getElementById("login")
.addEventListener("click", () => { keycloak.login(); });
}).error(err => {
console.log("init, error: " + err);
});
</script>
</head>
Response is a plain:
ERROR 404: Not Found
You have 2 posibilities :
invoque login automatically in init method
login manually after call init without params
1)
<head>
<script src="bower_components/keycloak/dist/keycloak.min.js"></script>
</head>
<body>
<button id="login">Login</button>
</body>
<script>
var keycloak = Keycloak({
url: 'https://keycloak-keycloak.192.168.37.1.nip.io',
realm: 'demo',
clientId: 'account'
});
keycloak.init('login-required')
.success(function(authenticated) => {
}).error(err => {
console.log("init, error: " + err);
});
</script>
</head>
2)
keycloak.init().success(function(authenticated) {
if(authenticated == true){
alert('usuario logeado');
}else{
alert('usuario no logeado');
keycloak.login();
}
}).error(function() {
alert('failed to initialize');
});
I had trouble trying directly from the management.
file://c:/example.html
To do a better test you should leave your index.html on a local test server.
What I did was install the web server plugin for chrome and it worked for me.
I hope it'll help you.
regards

Unable to attach any file to an HTML

Based on the tutorials I tried to set up a basic server in NodeJS via HapiJS.
The initialization looks like this:
//globals
mainAddr = "MoriMachine";
mainPort = 3000;
require('./backend/app.js')
This is the content of app.js:
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({host: mainAddr, port: mainPort });
server.register(require('inert'), (err) => {
if (err) { throw err; }
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply.file('./public/index/index.html');
}
});
});
server.start((err) => {
if (err) { throw err; }
console.log(`Server running at: ${server.info.uri}`);
});
While index.html is similarly small:
<!DOCTYPE html>
<html>
<head>
<script src="index.js"></script>
</head>
<body>
<h1>HELLO WORLD!! -3-</h1>
<img src="test.jpg"></img>
</body>
</html>
In the project itself, there are init.js and three folders:
node_modules: for obvious reasons
backend: contains app.js
public: contains folder 'index' that contains the HTML, and the JS and the picture I tried to attach.
The problem is that whatever path I try, when I run the server, neither the JS or the picture are found.
What is the reason? An I missing to add some additional functionality?
The reason is that you only got one route that serves one specific file. When you access the route '/' your browser tries to access '/index.js' and '/test.jpg' and you are not responding to these routes.
One way to do is is to serve everything in your public directory, like this:
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: 'public'
}
}
});
Now your index.js is accessible trough /index/index.js and your image is accessible trough /index/test.jpg
so make these changes to your html
<!DOCTYPE html>
<html>
<head>
<script src="/index/index.js"></script>
</head>
<body>
<h1>HELLO WORLD!! -3-</h1>
<img src="/index/test.jpg"></img>
</body>
</html>
Note that in this way your index.html is also accessible trough /index/index.html
for more detaisl look at: http://hapijs.com/tutorials/serving-files?lang=en_US#directory-handler

Browserify global variable is not found in the browser

I am writing a script in TypeScript, and when I use browserify, to convert it, my master variable is not found in the browser.
main.ts
import { GameSmart } from './GameSmart';
const gamesmart = new GameSmart();
gulpfile.js
/* require's snipped */
gulp.task('build', function () {
return browserify()
.add('./src/gamesmart/main.ts')
.plugin(tsify)
.bundle()
.on('error', function (error) {
console.error(error);
throw error;
})
.pipe(source('gamesmart.js'))
.pipe(gulp.dest('build/'));
});
In my page I am including the newly created file, and attempting to call the gamesmart variable, but it is not found.
<script scr="/path/to/sdk.js">
<script>
gamesmart.game.started();
</script>
How can I make it as a global/root variable?
I was able to fix this by adding the variable to the window.
window['gamesmart'] = new GameSmart();

Categories

Resources