Unexpected token < in first line of HTML - javascript

I have an HTML file :
<!DOCTYPE HTML>
<html lang="en-US" ng-app="Todo">
<head>
<meta charset="UTF-8">
<title>DemoAPI</title>
<meta name="viewport">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<link rel="stylesheet" href="./Client/css/styling.css" />
<script type="text/javascript" src="core.js"></script>
</head>
The error says:
Uncaught SyntaxError: Unexpected token < core.js: 1
It shows the error at <!doctype html> of the app.html.
core.js looks like this:
angular.module('Todo', [])
.controller('mainController', function($scope, $http)
{
$scope.formData = {};
// get all and show them
$http.get('/musicians')
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
//get with an id
$scope.getOneTodo = function() {
$http.get('/musicians' + id)
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
// send the text to the node API
$scope.createTodo = function() {
$http.post('/musicians', $scope.formData)
.success(function(data) {
$scope.formData = {}; // clear the form
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
})
};
// delete
$scope.deleteTodo = function(id) {
$http.delete('/musicians' + id)
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
/*
$scope.updateTodo = function(id) {
$http.delete('/musicians' + id)
.success(function(data) {
$scope.todos = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};*/
});
It also gives me Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.14/$injector/modulerr?p0=Todo&p1=Error%3A%2…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A17%3A381)
Besides, in console, when I click at core.js, it shows the contents of app.html and name it core.js.
Here is the snapshot:
Also, as in the image, when I click index.html, it shows app.html. However, I do not have any file that is named index.html and I load app.html by default instead of index.html.
I have tried adding/removing type="text/javascript" but no help with that either.
Also, status 200 is returned on get request for core.js.
What might be wrong?

Your page references a Javascript file at /Client/public/core.js.
This file probably can't be found, producing either the website's frontpage or an HTML error page instead. This is a pretty common issue for eg. websites running on an Apache server where paths are redirected by default to index.php.
If that's the case, make sure you replace /Client/public/core.js in your script tag <script type="text/javascript" src="/Client/public/core.js"></script> with the correct file path or put the missing file core.js at location /Client/public/ to fix your error!
If you do already find a file named core.js at /Client/public/ and the browser still produces a HTML page instead, check the permissions for folder and file. Either of these might be lacking the proper permissions.

In my case I got this error because of a line
<script src="#"></script>
Chrome tried to interpret the current HTML file then as javascript.

I experienced this error with my WordPress site but I saw that there were two indexes showing in my developer tools sources.
Chrome Developer Tool Error
So I had the thought that if there are two indexes starting at the first line of code then there's a replication and they're conflicting with each other. So I thought that then perhaps it's my HTML minification from my caching plugin tool.
So I turned off the HTML minify setting and deleted my cache. And poof! It worked!

Check your encoding, i got something similar once because of the BOM.
Make sure the core.js file is encoded in utf-8 without BOM

Well... I flipped the internet upside down three times but did not find anything that might help me because it was a Drupal project rather than other scenarios people described.
My problem was that someone in the project added a js which his address was: <script src="http://base_url/?p4sxbt"></script> and it was attached in this way:
drupal_add_js('',
array('scope' => 'footer', 'weight' => 5)
);
Hope this will help someone in the future.

We had the same problem sometime ago where a site suddenly began giving this error. The reason was that a js include was temporarily remarked with a # (i.e. src="#./js...").

I had this problem in an ASP.NET application, specifically a Web Forms.
I was forcing a redirect in Global.asax, but I forgot to check if the request was for resources like css, javascript, etc. I just had to add the following checks:
VB.NET
If Not Response.IsRequestBeingRedirected _
And Not Request.Url.AbsoluteUri.Contains(".WebResource") _
And Not Request.Url.AbsoluteUri.Contains(".css") _
And Not Request.Url.AbsoluteUri.Contains(".js") _
And Not Request.Url.AbsoluteUri.Contains("images/") _
And Not Request.Url.AbsoluteUri.Contains("favicon") Then
Response.Redirect("~/change-password.aspx")
End If
I was forcing logged users which hadn't change their passwords for a long time, to be redirected to the change-password.aspx page. I believe there is a better way to check this, but for now, this worked. Should I find a better solution, I edit my answer.

For me this was a case that the Script path wouldn't load - I had incorrectly linked it. Check your script files - even if no path error is reported - actually load.

I had the same issue. I published the angular/core application on iis.
To change the Identity of the application pool solved my issue. Now the Identity is LocalSystem

I also faced same issue.
In my case when I changed script attribute src to correct path error got fixed.
<script src="correct path"> </script>

I got my problem fix by removing slash / at the and of link tag.
<link rel="manifest" type="application/manifest+json" href="https://kal.my.id/manifest.webmanifest" title="YakaLee">
i seen your's
<link rel="stylesheet" href="./Client/css/styling.css" />
try remove the slash like so:
<link rel="stylesheet" href="./Client/css/styling.css">

I was facing the same issue recently. The js path which I provided inside my HTML file was correct. Still, during the time of calling the js file, it was prompting me an uncaught exception in the console. Furthermore, my app is running fine on localhost but facing the issue on prod.
As the paths to js files are already correct, I just give it a try to change my calling .js file to another directly and change the root path and that worked.
Try changing the path of your .js file to another directory.

If someone around still have this issue as I had. Try adding this line of code to your header.
<base href="/" />
It will align your html file to the static directory on Nodejs you are setting.

Related

Accessing scala.js output in resources

I'm trying to build a application server using scala.js, scalatags, akka-http, and mill as my build tool. All goes well until the browser tries to find scripts with generated scala.js code. This is the scalatags code which successfully gets built and references the compiled scala.js code (HiPage.js - built as a ScalaJSModule in mill). When it is run the println below prints out:
file:/Users/nnovod/projects/lims/LIMS/resources/HiPage.js
which is indeed where I've placed the javascript output from scala.js
object HiPage {
val boot =
"Hi().main(document.getElementById('contents'))"
println(getClass.getResource("/HiPage.js").toString)
val skeleton =
html(
head(
script(`type`:="text/javascript", src:="/HiPage.js"),
link(
rel:="stylesheet",
href:="https://cdnjs.cloudflare.com/ajax/libs/pure/0.5.0/pure-min.css"
)
),
body(
onload:=boot,
div(id:="contents")
)
)
}
This eventually shows up in the browser as follows:
<html>
<head>
<script type="text/javascript" src="/HiPage.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pure/0.5.0/pure-min.css"/>
</head>
<body onload="Hi().main(document.getElementById('contents'))">
<div id="contents"></div>
</body>
</html>
This is my akka-http route...
val route =
path("hello") {
get {
complete(
HttpEntity(
ContentTypes.`text/html(UTF-8)`,
HiPage.skeleton.render
)
)
}
}
The browser can never find the HiPage.js ("Failed to load resource: the server responded with a status of 404 (Not Found)"). HiPage.js is in a top level resources directory and is found by the println(getClass.getResource("/HiPage.js").toString) in the code. What do I have to do to get it seen when the browser requests it from the server?
Not sure if this is the best way but I finally was able to solve the problem by having all src references in script start with /resource and then editing my akka-http route to include the following:
pathPrefix("resource") {
extractUnmatchedPath { unmatched =>
val resource = unmatched.toString()
if (!resource.startsWith("/"))
reject()
else
getFromResource(resource.substring(1))
}
}

include the JS source in the existing *.js file

I have MqttConnect.js file and mqttws31.js lib . I have to mqttws31.js all source code include my MqttConnect.js file, How it possible?.
when I copy everything from mqttws31.js and past mqttconnect.js file .that time this error occur:
ReferenceError: Messaging is not defined
if I try this way it is working fine :
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script src="http://www.hivemq.com/demos/websocket-client/js/mqttws31.js" type="text/javascript"></script>
<script src="MqttJS/MqttConnect.js"></script>
</head>
MqttConnect.js file code :
// Using the HiveMQ public Broker, with a random client Id
var client = new Messaging.Client("broker.mqttdashboard.com",8000, "myclientid_" + parseInt(Math.random() * 100, 10));
//Connect Options
var options = {
timeout: 60,
keepAliveInterval:450,
cleanSession:false,
//Gets Called if the connection has sucessfully been established
onSuccess: function () {
alert("Connected:");
},
//Gets Called if the connection could not be established
onFailure: function (message) {
alert("Connection failed -: " + message.errorMessage);
}
};
function Connect(){
try {
client.connect(options)
}
catch(err){
alert(err.message);
}
}
mqttws31.js code:
http://www.hivemq.com/demos/websocket-client/js/mqttws31.js
UPDATE
where I want use this , there have no html page
This may be due to a quirk of how JavaScript loads. You can find a good example of how it should be done in this answer.
The quick answer is to place the loading of both JavaScript files into the body of the HTML document hosting them, with the MQTT library above your script.
Do NOT just copy the library into your own file, that's very poor form and a copyright violation if you don't credit the library's source properly.
Copy content of mqttws31.js into MqttConnect.js at the top (not at the bottom) and then load MqttConnect.js file:
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script src="MqttJS/MqttConnect.js"></script>
</head>
I tried this myself, I am not getting any error. (window is undefined)
There is a dependency between the two files, that is, there is code in MqttConnect.js which needs the code in mqttws31.js in order to work properly. So I'm assuming you pasted the contents of mqttws31.js at the end of MqttConnect.js. Pasting the contents of mqttws31.js at the beginning of MqttConnect.js should fix this. Your MqttConnect.js should look like
// Contents of mqttws31.js ...
// Contents of MqttConnect.js ...

Prefetching $templateCache

My angularjs application basically loads in 4 steps:
main HTML
all scripts and CSS files
$templateCache, let's call it template.html
images
I guess, I should bypass the $templateCache when loading the starting page. But for now, I'd like to start fetching template.html ASAP, i.e., at the same time as the scripts get loaded.
The possibly relevant piece of my code looks like
<script src='//ajax.googleapis.com/.../angular.min.js'></script>
<script src='/my.js'></script>
<link href='/my.css' media='all' rel='stylesheet'/>
Here, my.js contains all my scripts and gets loaded at the same time as angular. Is there something allowing me to fetch template.html in the same way, so it gets put into the browser's cache?
Update
I've tried two prefetching possibilities, both failed:
<link href="template.html" rel="prefetch"/>
and
<iframe class=invisible src="template.html"></iframe>
The first gets cancelled and the second comes too late to be effective.
As the HTML can't be fetch soon enough, the whole script directive is completely pointless.
According to runTarm's suggestion, I ended up generating the Javascript instead. All it takes is
.factory('$templateCache', function($cacheFactory, $http, $injector) {
var cache = $cacheFactory('templates');
cache.put("MY_PAGE_1", "ESCAPED_TEXT_1");
cache.put("MY_PAGE_2", "ESCAPED_TEXT_2");
...
return {
get: function(url) {
var fromCache = cache.get(url);
return fromCache ? fromCache : $http.get(url);
}
};
}
In the escaped text you must honor the 1024 string-literal length limit and escape newlines and double quotes. That's all.

Getting a JSON file using jQuery without a web server

I had a coding interview quiz for front-end working with JSON and whatnot. I submitted my file but I'd just like to learn what I was missing.
And one of the reqs was Should not require a web server, and should be able to run offline..
I used jQuery and used $.getJSON() to get the data from the .JSON file. I threw it up on my WAMP localserver and it worked flawlessly across all three major browsers (IE, Firefox, Chrome). Then I moved that project to Desktop, so essentally, without a LOCALSERVER.
On Firefox 30.0, it worked great. No problems.
Oon Google Chrome, I know you can't access local files without a web server...
On Internet Explorer 11, however... it didn't work. Why?
Here is what I am using. It's not complex.
function loadTasks() {
console.log("Loading tasks...");
$.getJSON("data.json", function(result) {
$.each(result, function(i, task) {
$("#load_tasks").append(
"<div class='row'><span class='data-task'>" + task.name +
"</span> <span class='data-date'>" + task.date +
"</span> <span class='data-name'>" + task.assigned +
"</span> </div>");
});
});
}
and here is data.json
This seems to be a bug in jQuery. This bug has been reported to jQuery. The bugs status is fixed. But it seems, the bug is still at large.
Explanation
Generally in IE, ajax is implemented through ActiveXObjects. But in IE11, they made some tweaks to ActiveXObject implementation that if we try to do the following:
typeof(window.ActiveXObject)
instead of returning 'function', as it is said in IE docs, it returns undefined. jQuery used to use this to switch between xhr in normal browsers and between one in IE. Since the check evaluates to undefined, code used to create xhr object in normal browsers is run.(which of-course is a bug, strangely, for non-local files it working fine).
In a bug filed to bugs.jquery.com, the bug reporter asks,
To fix the problem it's enough to change the condition: use
"window.ActiveXObject !== undefined ?" instead of
"window.ActiveXObject ?"
jQuery developers does try to fix this with this commit, but the comment under the commit says its still not fixed and also suggests a possible way to approach this problem.
var activex; // save activex somewhere so that it only need to check once
if ( activex === undefined )
try {
new ActiveXObject("MSXML2.XMLHTTP.3.0");
activex = true;
} catch (e) {
activex = false
}
xhr = activex ? createActiveXHR() : createStandardXHR();
I tried running your code in my machine and it works fine in IE.
However if this is not running in your machine there should be some issue with IE settings. Apart from this if you want to read local file you can try the below code to resolve this issue for IE
function showData(){
function getLocalPath(fileName/*file name assuming in same directory*/){
// Remove any location or query part of the URL
var directoryPath = window.location.href.split("#")[0].split("?")[0];
var localPath;
if (directoryPath.charAt(9) == ":") {
localPath = unescape(directoryPath.substr(8)).replace(new RegExp("/","g"),"\\");
}
localPath = localPath.substring(0, localPath.lastIndexOf("\\")+1)+fileName;
console.log(localPath);
return localPath;
}
var content = null;
try {
var fileSystemObj = new ActiveXObject("Scripting.FileSystemObject");
var file = fileSystemObj.OpenTextFile(getLocalPath("data.json"),1);
content = file.ReadAll();
file.Close();
} catch(ex) {
console.log(ex);
}
console.log(content);
}
showData();
Run your html file in browser from file path and try running above function in console. It will output the content of json file in console.
You can create a wrapper for above code to use in XHR request. Let me know if you need help in integrating this with jQuery AJAX request.
What you we're missing was the use of appCache,
<html manifest="example.appcache">
in your HTACCESS add
AddType text/cache-manifest .appcache
inside example.appcache
CACHE MANIFEST
data.json
index.php
someimage.png
# continue for all the file needed for the web site to work
This means that once you have connected and downloaded the content once it's not needed again. on another note you not supposed to be able to access a file:// URI though XHR/ajax as there is no way to send the content if you wanted it offline you could have just embedded the content of the json file into you code as a string and just use var jsonStr = '{}'; var jsonObj = JSON.parse(jsonStr); where jsonStr is you code. this would have meant no connections to the server as there would be no ajax/XHR request
jQuery .getJSON uses ajax. http://api.jquery.com/jquery.getjson/
.ajax uses a XMLHttpRequest
The web security of chrome and other browsers block XMLHttpRequest to local files because it is a security issue.
Via Security in Depth: Local Web Pages
http://blog.chromium.org/2008/12/security-in-depth-local-web-pages.html
You receive an email message from an attacker containing a web page as
an attachment, which you download.
You open the now-local web page in your browser.
The local web page creates an iframe whose source is
https://mail.google.com/mail/.
Because you are logged in to Gmail, the frame loads the messages in
your inbox.
The local web page reads the contents of the frame by using JavaScript
to access frames[0].document.documentElement.innerHTML. (An Internet
web page would not be able to perform this step because it would come
from a non-Gmail origin; the same-origin policy would cause the read
to fail.)
The local web page places the contents of your inbox into a
and submits the data via a form POST to the attacker's web server. Now
the attacker has your inbox, which may be useful for spamming or
identify theft.
The solution for data which does not need same-origin policy security, is padded json. Since jsonp is not a secure format for data. Jsonp does not have the same-origin policy.
/* secured json */
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
/* padded json aka jsonp */
Mycallback ({
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
});
Since with jsonp the json is wrapped in a valid javascript function it can be opened the same way as any one would add any javascript to a page.
var element = document.createElement("script");
element.src = "jsonp.js";
document.body.appendChild(element);
And your callback processes the data,
function Mycallback(jsondata) {
}
This is functionally the same as a ajax request but different because it is a jsonp request, which is actually easier.
jQuery libs do directly support jsonp as well http://api.jquery.com/jquery.getjson/ See the example using Flickr's JSONP API; unless one was aware of the dual standards they may not even notice that jsonp is being used.
(function() { /* jsonp request note callback in url, otherwise same json*/
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, {
tags: "mount rainier",
tagmode: "any",
format: "json"
})
.done(function( data ) {
$.each( data.items, function( i, item ) {
$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
if ( i === 3 ) {
return false;
}
});
});
})();
Local access to json can be enabled but it is done differently depending on browswer.
Use --allow-file-access-from-files to enable it in chrome. https://code.google.com/p/chromium/issues/detail?id=40787
FYI: they are working on encripted json https://datatracker.ietf.org/doc/html/draft-ietf-jose-json-web-encryption-08 I am fairly certain that there will be no method of using this locally the intention is to make it really, really secure.
Source: https://stackoverflow.com/a/22368301/1845953
Posting the answer just in case somebody else runs into it. In my case
IE was loading a version of jquery that apparently causes "JSON
undefined" error. Here is what I did to solve it:
<!--[if lt IE 9]>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<![endif]-->
<!--[if gte IE 9]><!-->
<script src="http://code.jquery.com/jquery-2.0.3.js"></script>
<!--<![endif]-->
The latest one is jquery 2.1.1: direct link but it says:
(IE <9 not supported)
So I guess jquery 1.11.1: direct link
And I found out you can develop ajax and jquery stuff in Chrome on local files if you use Chrome with this flag: --allow-file-access-from-files (source)
<meta http-equiv="X-UA-Compatible" content="IE=edge">
Try adding this meta tag and check in IE
Here's a working solution.
I've included handlebars because it's cleaner.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>JSON TEST</title>
</head>
<body>
<div id="load-tasks">
</div>
<script src="jquery.min.js"></script>
<script src="handlebars.min.js"></script>
<script id="tasks-template" type="text/x-handlebars-template">
{{#each .}}
<div class="row">
<span class="data-task">
{{this.name}}
</span> <span class="data-date">
{{this.date}}
</span> <span class="data-name">
{{this.assigned}}
</span>
</div>
{{/each}}
</script>
<script>
$(function () {
var loadTasksContainer = $('#load-tasks'),
tasksTemplate = Handlebars.compile($('#tasks-template').html());
$.ajax({
type: "GET",
url: "data.json",
dataType: "json",
cache: false,
success: function (data) {
var html = tasksTemplate(data);
loadTasksContainer.append(html);
},
error: function (xhr, status, error) {
//log error and status
}
});
});
</script>
</body>
</html>
Using JSONP you could make this work for all browsers with or without a web server or even cross domain.
Example data.jsonp file:
loadTasks([
{name:"Task 1", date:"Date 1", assigned:"John Doe"},
{name:"Task 2", date:"Date 2", assigned:"Jane Doe"}
]);
Then on your page just load the data.jsonp using a script tag:
<script>
function loadTasks(tasks) {
$.each(tasks, function (i, task) {
$("#load_tasks").append(
"<div class='row'><span class='data-task'>" + task.name +
"</span> <span class='data-date'>" + task.date +
"</span> <span class='data-name'>" + task.assigned +
"</span> </div>");
});
}
</script>
<script src="data.jsonp"></script>
Try including an error callback ; jqxhr.responseText may still contain data.json .
data.json
{"data":{"abc":[123]}}
json.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON(document.location.protocol + "data.json")
.then(function(data, textStatus, jqxhr) {
var response = JSON.parse(data);
console.log(textStatus, response);
}
// `error` callback
, function(jqxhr, textStatus, errorThrown) {
var response = JSON.parse(jqxhr.responseText);
console.log(textStatus, errorThrown, response);
$("body").append(response.data.abc);
});
})
</script>
</head>
<body>
</body>
</html>
Dealing with this problem will lead you to anywhere. It is a difficult task and it could be easily solved using any http server.
If your problem is that it is difficult to set up one, try this:
https://www.npmjs.org/package/http-server
On your shell you go to the directory where are your files and then you just type
http-server ./ -p 12345
where 12345 can be changed by any valid and not already used port of your choice.

JQuery .getJson wont load local file plus how to convert to JavaScript object.

Hey guys I am trying to learn how to use JSON files. I understand the basics but I am trying to grasp loading them into an HTML file and I am having a couple of difficulties.
The first difficulty I am having is that if I put in the full file extension to load the file I get an error 'expected hexadecimal digit'. I did some research on it and I think it is because in the file extension it is \u so it is expecting a hexadecimal but I am not sure how to work around it.
The second problem I am having is that if I just use the file extension users.json it works in my editor but not in a browser. It is not loading the file at all, the code is fine (I believe). I think it is just not loading the file because of the file extenion.
Suggestions on how to fix my problems? Thanks in advance.
<body>
for output
<div id="forOutput"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var output;
$(document).ready(function(){
alert("JQuery loaded");
});
$.getJSON('C:\Users\Spencer\Desktop\JSJqueryTesting\JSONTesting\users.json', function(data) {
output = data;
for (var i in data.users) {
alert(data.users[i].firstName + " " + data.users[i].lastName+ " " + data.users[i].joined.month);
}
});
$("#forOutput").html("User 1 lastname: " + output.users[1].lastName);
</script>
The file extension is perfect (.json), however, you can't load local files (because of security reasons). If what you are trying to do, were possible, that would mean any website could access all your local files. Now that's really not such a good idea, and therefore (by default) only files that share the same domain(e.g. stackoverflow.com/*) are allowed. This is called Same Origin Policy.

Categories