AngularJS Failing to Instantiate Module - javascript

For some reason, my angularjs module isn't loading correctly. I am pretty new to this and I've read a lot of tutorials, but I can't seem to get this working.
[17:22:36.338] Error: [$injector:modulerr] Failed to instantiate module wc2013mongoMod due to:
[$injector:nomod] Module 'wc2013mongoMod' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
I have found this question, which appears to be a very close description to my problem: AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?
It suggests re-arranging the order in which the scripts are included. I've tried to put the scripts at the end of the body, no luck. I've also tried to put them inside the <head> element, but still no luck. What am I doing wrong here?
I am using Jade, but the resulting HTML looks like this:
<!DOCTYPE html>
<html ng-app="wc2013mongoMod">
<head>
<title>World Cup 2014 MongoDB Experiment Project</title>
<link rel="stylesheet" href="/stylesheets/style.css">
<script src="js/angular/angular.js"></script><script src="js/main.js"></script>
</head>
<body>
<h1>World Cup 2014 MongoDB Experiment Project</h1>
<p>Welcome to World Cup 2014 MongoDB Experiment Project</p>
<div ng-controller="teamCtrl">
<p>Angular JS Controller</p>
</div>
</body>
</html>
The javascript looks like this:
console.log("loaded main.js");
var myApp = angular.module('wc2014mongoMod',[]);
myApp.service('teamService', function($http) {
//delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(callbackFunc) {
$http({
method: 'GET',
url: '/api'
//params: 'limit=10, sort_by=created:desc',
//headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
// With the data succesfully returned, call our callback
//callbackFunc(data);
console.log("data received");
console.log(data);
}).error(function(){
alert("error");
});
}
});
myApp.controller('teamCtrl', function($scope, teamService) {
$scope.data = null;
console.log("we're in the controller");
teamService.getData(function(dataResponse) {
$scope.data = dataResponse;
});
});

Check the difference. 2013 vs 2014.
<html ng-app="wc2013mongoMod">
and
var myApp = angular.module('wc2014mongoMod',[]);

You should spot the error given these two lines:
<html ng-app="wc2013mongoMod">
..
var myApp = angular.module('wc2014mongoMod',[]);
wc2013mongoMod !== wc2014mongoMod

Related

Node/Express - Refused to apply style because its MIME type [duplicate]

I'm starting with Node.js and I have already a problem in my first program. Below is the code I'm using. Index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Random Temperatures</title>
</head>
<body>
<input type="text" id="tb" name="tb" />
<input type="button" value="Random Number!" id="myButton" name="myButton"/>
<script src="client.js"></script>
</body>
</html>
Client.js:
const textBox = document.getElementById('tb');
const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
var rnd = Math.floor(Math.random() * 100);
textBox.value = rnd;
});
Server.js:
var app = require('http').createServer(response);
var fs = require('fs');
app.listen(8080);
console.log("App running…");
function response(req, res) {
fs.readFile(__dirname + '/public/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Failed to load file index.html');
}
res.writeHead(200);
res.end(data);
});
}
When I start the application I go to the browser the text box and the button appear. But in the browser console I'm getting these errors:
client.js:1 Uncaught SyntaxError: Unexpected token <
ContentScript.js:112 Exception in onResRdy: TypeError: Cannot read
property 'htmlRes' of undefined
localhost/:1 Unchecked runtime.lastError: Could not establish
connection. Receiving end does not exist.
I guess my problem is the linking between the 3 files but I tried several things and I can't solve the problem. I'm sure it's a stupid error but forgive me I'm just getting start. Any advice?
The browser (because you have <script src="/client.js">) makes a request for /client.js
The server:
Gets the request
Runs response
Reads index.html
Sends it to the browser
Since index.html starts with <, the browser throws an error when it tries to run it as JavaScript.
Why are you giving the browser index.html when it asks for client.js?
You need to examine the request object, determine what URL is being asked for, write logic to return the correct resource with the correct status code and the correct content-type, and then return that to the client.
The Node.js documentation has an example of this but you should probably stop trying to use createServer directly — since it involves a massive amount of wheel reinvention — switch to using Express and work through the (very short) getting started guide which includes a section on using the static module to serve up static files.

Is it possible to get the Woocommerce JavaScript api to work in browser?

Instead of making a PHP/JavaScript hybrid, I wanted to learn something new and go with a JavaScript implementation. I am following the official documentation: https://www.npmjs.com/package/#woocommerce/woocommerce-rest-api
I have installed node.js, and installed the package as instructed, using npm, to the folder C:\wamp\www\blah. I have created a new project to my Wampserver, which I access in the browser via http://localhost/blah. I ran cmd, did cd wamp\www\blah and then npm i #woocommerce/woocommerce-rest-api. So I'll assume the necessary files should be in the correct location.
This is what my index.html looks like:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="require.js"></script>
<script src="js.js"></script>
</head>
<body>
<div>TODO write content</div>
</body>
</html>
And this is what my js.js looks like:
import WooCommerceRestApi from "#woocommerce/woocommerce-rest-api";
//const WooCommerceRestApi = require("#woocommerce/woocommerce-rest-api").default;
const api = new WooCommerceRestApi({
url: "http://example.com",
consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
version: "wc/v3"
});
// List products
api.get("products", {
per_page: 20 // 20 products per page
})
.then((response) => {
// Successful request
console.log("Response Status:", response.status);
console.log("Response Headers:", response.headers);
console.log("Response Data:", response.data);
console.log("Total of pages:", response.headers['x-wp-totalpages']);
console.log("Total of items:", response.headers['x-wp-total']);
})
.catch((error) => {
// Invalid request, for 4xx and 5xx statuses
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
})
.finally(() => {
// Always executed.
});
What I get in the console is this:
Uncaught SyntaxError: import declarations may only appear at top level of a module
Some solutions have suggested that I need a type="module" attribute in the <script> tag. Tried it, alone made no difference. One solution suggested that I should change line 1 to this:
import {WooCommerceRestApi} from "./node_modules/#woocommerce/woocommerce-rest-api";
The error I get now is this:
Loading module from “http://localhost/blah/node_modules/#woocommerce/woocommerce-rest-api/” was blocked because of a disallowed MIME type (“text/html”).
Sheesh. More googling suggested that I must import the actual file, not just a package. So I did this:
import {WooCommerceRestApi} from "./node_modules/#woocommerce/woocommerce-rest-api/index.js";
The error I get now is this:
Uncaught SyntaxError: ambiguous indirect export: WooCommerceRestApi
This is going nowhere. So next I tried the "common javascript" approach. I commented out line 1 and enabled line 2:
//import WooCommerceRestApi from "#woocommerce/woocommerce-rest-api";
const WooCommerceRestApi = require("#woocommerce/woocommerce-rest-api").default;
What I get now is this:
Uncaught ReferenceError: require is not defined
I did some googling and a suggested solution was that I am missing a dependency, require.js, which I downloaded and added to the project (hence the <script src="require.js"></script> line). Now I get this error message:
Uncaught Error: Module name "#woocommerce/woocommerce-rest-api" has not been loaded yet for context: _. Use require([])
Could've been written in Hebrew and I would've understood just as much, but since there is a suggested solution there, I add some brackets to line 2:
const WooCommerceRestApi = require(["#woocommerce/woocommerce-rest-api"]).default;
The error I get now is this:
Uncaught TypeError: WooCommerceRestApi is not a constructor
I am starting to wonder if the reason for why this is so painful is that it just is not supposed to be used this way? Could that also be the reason why I have not been able to find an exemplary implementation of this? But which way should it be used then? Is writing some code and hitting F5 just not the way anymore? Do I have to compile something? What am I missing here?

HTML Script tag pointing to external source not working [duplicate]

I'm starting with Node.js and I have already a problem in my first program. Below is the code I'm using. Index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Random Temperatures</title>
</head>
<body>
<input type="text" id="tb" name="tb" />
<input type="button" value="Random Number!" id="myButton" name="myButton"/>
<script src="client.js"></script>
</body>
</html>
Client.js:
const textBox = document.getElementById('tb');
const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
var rnd = Math.floor(Math.random() * 100);
textBox.value = rnd;
});
Server.js:
var app = require('http').createServer(response);
var fs = require('fs');
app.listen(8080);
console.log("App running…");
function response(req, res) {
fs.readFile(__dirname + '/public/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Failed to load file index.html');
}
res.writeHead(200);
res.end(data);
});
}
When I start the application I go to the browser the text box and the button appear. But in the browser console I'm getting these errors:
client.js:1 Uncaught SyntaxError: Unexpected token <
ContentScript.js:112 Exception in onResRdy: TypeError: Cannot read
property 'htmlRes' of undefined
localhost/:1 Unchecked runtime.lastError: Could not establish
connection. Receiving end does not exist.
I guess my problem is the linking between the 3 files but I tried several things and I can't solve the problem. I'm sure it's a stupid error but forgive me I'm just getting start. Any advice?
The browser (because you have <script src="/client.js">) makes a request for /client.js
The server:
Gets the request
Runs response
Reads index.html
Sends it to the browser
Since index.html starts with <, the browser throws an error when it tries to run it as JavaScript.
Why are you giving the browser index.html when it asks for client.js?
You need to examine the request object, determine what URL is being asked for, write logic to return the correct resource with the correct status code and the correct content-type, and then return that to the client.
The Node.js documentation has an example of this but you should probably stop trying to use createServer directly — since it involves a massive amount of wheel reinvention — switch to using Express and work through the (very short) getting started guide which includes a section on using the static module to serve up static files.

Elasticsearch : Uncaught ReferenceError: elasticsearch is not defined

I am trying to create a NodeJS application using Elasticsearch
here is my code
<!DOCTYPE html>
<script src="../bower_components/elasticsearch/elasticsearch.js"></script>
<script>
function esPinger() {
var elasticsearch = require('elasticsearch');
var client = elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});
client.ping({
// ping usually has a 3000ms timeout
requestTimeout: Infinity,
// undocumented params are appended to the query string
hello: "elasticsearch!"
}, function (error) {
if (error) {
console.trace('elasticsearch cluster is down!');
} else {
console.log('All is well');
alert("YAY");
}
});
}
</script>
<html>
<head>
<title>NodeJS Starter Application</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="stylesheets/style.css">
</head>
<body>
<center>
<button onclick="esPinger()">Ping ES</button>
</center>
</body>
</html>
i installed the elasticsearch client as
npm install elasticsearch
and also
bower install elasticsearch
in my project folder, i can see that there is a bower_componenets folder that has all of the .js files for elasticsearch, including elasticsearch.js
now, when i run my page and click on the button, i get
Uncaught ReferenceError: elasticsearch is not defined
any idea why? am i missing some configuration?
for reference, here is what my project structure looks like
Edit
Here is what i see in the inspect element console
how can it not get the library!
Node.JS is a server-side technology, not a browser technology. Thus, Node-specific calls, like
var elasticsearch = require('elasticsearch');
do not work in the browser.

angularjs Error: [$compile:tpload] Failed to load template

I am trying to build simple routing app in angularjs. I have main index.html page with ng-view div and javascript code for routing. Also 2 simple html pages view2.html and view3.html placed in sub folder partials1.
I am getting below error. Please help.
Error: Access is denied.
Error: [$compile:tpload] Failed to load template: partials1/view3.html
http://errors.angularjs.org/1.3.15/$compile/tpload?p0=partials1%2Fview3.html
index.html:
<div data-ng-view></div>
<script src="angular.js"></script>
<script src="angular-route.js"></script>
<script type="text/javascript">
var demoApp = angular.module('demoApp', [ 'ngRoute' ]);
demoApp.controller('SimpleController', function($scope) {
$scope.customers = [ {
name : 'Jon Smith1',
city : 'Charlotte'
}, {
name : 'John Doe',
city : 'New York'
}, {
name : 'Jane Doe',
city : 'Jacksonville'
} ];
});
demoApp.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl : 'partials1/view3.html',
controller : 'SimpleController'
}).when('/view2', {
templateUrl : 'partials1/view2.html',
controller : 'SimpleController'
}).otherwise({
redirectTo : '/view1'
});
} ]);
</script>
view2.html
<div class="container">33333333333333</div>
view3.html
<div class="container">33333333333333</div>
Error: Access is denied tells you that the template is not accessible. Try to open the template in your browser. Something like this: http://my_project/partials1/view3.html. To see the full URL which is used by your app, use a dubug console (XHR tab).
Error: [$compile:tpload] Failed to load template: xyz.html (HTTP status: 404 Not Found)
can be caused by below setting in web.config
<system.webServer>
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
This causes to block any direct request to the file in Views directory. Angular xhr request to this file is blocked by this.
Comment it out and see if things work. Use this with caution as it allows access to your files.
You can also check on this url for more responses: Error: $compile:tpload failed to load template Http status : 404
In my case, the issue is that I added Default Headers such as Accept = 'application/json'. So my routes suddenly stopped working, because those headers were not only applied to my $http.post calls, they were also applied to my Routing... ? Weird.
I had the same error, in my case the web server was written with node js and the uri to get views that were in the specified path with $stateProvider was not created, since for each view/template that is wanted to display an http request of type Xhr GET is made.
As the uri did not exist I obtained a 404 code and this made the browser got into callback that killed him. Make sure your server is returning the requested view. (Translated with google translate)

Categories

Resources