Getting 404 error when trying to access local files - javascript

I am trying to make a very simple html with local server that displays all images in a local directory (content folder). But I am getting jquery-3.2.1.min.js:4 GET http://localhost:8080/content/ 404 (Not Found)
So, my file structure looks like:
rootfolder
-content/
-js/
-index.html
-server.js
server.js looks like this:
var connect = require('connect')
var serveStatic = require('serve-static')
connect().use(serveStatic(__dirname)).listen(8080, function () {
console.log('Server running on 8080...')
console.log('dirname', __dirname)
})
index.html like this:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div id="img-container">
</div>
</body>
</html>
index.js looks like this:
window.onload = function () {
var folder = 'content/'
$.ajax({
url: folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if (val.match(/\.(jpe?g|png|gif)$/)) {
$("body").append( "<img src='"+ folder + val +"'>" )
}
})
}
})
console.log('test2')
}
The code isn't very clean at the moment but I want to figure out why I am getting 404 Not Found error first.

Related

web worker throwing 404 when executing

My project structure looks like
js
/client.js
/script1.js
/webWoker.js
node_modules
.gitignore
index.html
The main.html has it included as well in
<script type="text/javascript" src="js/script1.js"></script>
<script type="text/javascript" src="js/client.js"></script>
<script type="text/javascript" src="js/webWoker.js"></script>
My script1.js looks like
if (window.Worker) {
console.log("uri: " + document.documentURI);
var myWorker = new Worker("myworker.js");
myWorker.postMessage("hello");
console.log(myWorker);
myWorker.onmessage = function (e) {
result.textContent = e.data;
console.log('Message received from worker: ' + result.textContent);
};
}
and my webWorker.js looks like
onmessage = function (e) {
console.log('Message received from main script');
var result = "#27ae60";
console.log('Posting message back to main script');
postMessage(result);
};
I use node.js for this project and run it via npm start, and when I run this in browser I see
script1.js:81 GET http://localhost:8080/webWorker.js 404 (Not Found)
execute # script1.js:81
img.onload # script1.js:64
What is going wrong here?
You don't have to include the worker script in your main page (it's even a bad idea), but the URI you pass to new Worker(URI) is relative to the current documentURI.
So in your case, it should be new Worker("/js/webWorker.js");.

html file cannot find uploads directory

I have an html file that is supposed to display every picture in the uploads directory, however it does not recognize an uploads directory. I am using a nodejs server. Here is my html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>gummy bear</title>
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link href="css/styles.css" rel="stylesheet">
</head>
<body>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script>
var dir = "/uploads/";
var fileextension = ".jpg";
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='" + dir + filename + "'>");
});
}
});
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
and here is what my directory layout looks like:
app.js css index.html javascripts LICENSE node_modules package.json README.md upload.html uploads
and inside of uploads is:
➜ uploads ls
1.jpg
Thanks in advance!
Looking through the sample code it seems like the HTML file expects some HTML to be returned from http://localhost:3000/uploads.
The questions is why does the /uploads endpoint not return anything but instead returns a 404 response?
The answer to this would lie in the main executable Javascript file in the node.js application. Likely a file called server.js or index.js.
Here is an example of how you would go about creating the correct node.js application for you HTML file to work:
server.js
app.all('/uploads', function (req, res) {
var folder = './public/uploads',
html = '<html><body>##files##</body></html>';
fs.readdir(folder, (err, files) => {
var fileHrefs = '';
files.forEach(function (file) {
fileHrefs += '' + file + '';
});
html = html.replace('##files##', fileHrefs);
res.send(err || html);
})
});
This snippet of code iterates over all files in the uploads directory and wraps them in an a tag which is then returned by the server.
index.html
To make your index HTML file work a couple small changes need to be made:
change $(data).find() to $(data).filter()
remove the directory from the image source. change <img src='" + dir + filename + "'> to <img src='" + filename + "'>
Complete working sample
You can also find the whole working sample here: https://github.com/kohlikohl/list-images-in-dir

Failing to get simple SoundCloud javascript api method to work

I have the following code below :
<!DOCTYPE html>
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207",{}, function(user){
console.log("in the function w/ " + user);
});
</script>
</head>
</html>
The code should print the user name to the console however whenever I run this, my console gives the error of :
Failed to load resource: The requested URL was not found on this server:
file://api.soundcloud.com/users/3207?client_id=f520d2d8f80c87079a0dc7d90db9afa9&format=json&_status_code_map%5B302%5D=200
However if I were to directly http://api.soundcloud.com/users/3207.json?client_id=f520d2d8f80c87079a0dc7d90db9afa9, then I get a valid JSON result.
Is there something incorrect with my how I am using the SC.get function?
Thanks
Well, you should test your index.html locally on a web-server like Apache and not by opening it as a file.
Working example
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207", {}, function(user) {
console.log("in the function w/ " + JSON.stringify(user));
var res = document.getElementById("result");
res.innerHTML = JSON.stringify(user);
});
<script src="http://connect.soundcloud.com/sdk.js"></script>
<div id="result"></div>

Youtube Data Api - Uncaught TypeError: Cannot read property 'setApiKey' of undefined

I search music with youtube data api. I use javascript and jquery and i have a problem.
Here is my code
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="<?php echo SITE_PUBLIC; ?>/bootstrap-3.2.0/dist/js/bootstrap.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
<script>
function keyWordsearch(){
gapi.client.setApiKey('myapikey');
gapi.client.load('youtube', 'v3', function() {
data = jQuery.parseJSON( '{ "data": [{"name":"eminem"},{"name":"shakira"}] }' );
$.each(data["data"], function( index, value ) {
makeRequest(value["name"]);
});
});
}
function makeRequest(q) {
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 10
});
request.execute(function(response) {
$('#results').empty()
var srchItems = response.result.items;
$.each(srchItems, function(index, item) {
vidTitle = item.snippet.title;
vidThumburl = item.snippet.thumbnails.default.url;
vidThumbimg = '<pre><img id="thumb" src="'+vidThumburl+'" alt="No Image Available." style="width:204px;height:128px"></pre>';
$('#results').append('<pre>' + vidTitle + vidThumbimg + '</pre>');
})
})
}
keyWordsearch();
</script>
This code not working. Chrome console say "Uncaught TypeError: Cannot read property 'setApiKey' of undefined". But this code is working:
keyWordsearch() to
$(document).click(function(){
keyWordsearch()
})
I do not understand this issue. Thanks in advance
EDIT
My code run on jsFiddle.But not run my html file. My html file is here:
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="container">
<h1>Search Results</h1>
<ul id="results"></ul>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
<script>
$(function(){
function keyWordsearch(){
gapi.client.setApiKey('AIzaSyCWzGO9Vo1eYOW4R4ooPdoFLmNk6zkc0Jw');
gapi.client.load('youtube', 'v3', function() {
data = jQuery.parseJSON( '{ "data": [{"name":"eminem"}] }' );
$.each(data["data"], function( index, value ) {
makeRequest(value["name"]);
});
});
}
function makeRequest(q) {
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 10
});
request.execute(function(response) {
$('#results').empty()
var srchItems = response.result.items;
$.each(srchItems, function(index, item) {
vidTitle = item.snippet.title;
vidThumburl = item.snippet.thumbnails.default.url;
vidThumbimg = '<pre><img id="thumb" src="'+vidThumburl+'" alt="No Image Available." style="width:204px;height:128px"></pre>';
$('#results').append('<pre>' + vidTitle + vidThumbimg + '</pre>');
})
})
}
keyWordsearch();
})
</script>
</body>
</html>
Looks like, you haven't load the javascript library. That's why it can't find the reference.
You can add it like:
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
You can specify an initial function while calling the API like this: client.js?onload=init (see my example below). Besides no need of a doucument.ready() wrapper. I'm not sure why it works with your API key on my local machine but I guess it's some kind of magic that checks if the site is availible to the public - if true the referrer entries in your google account will get important - correct me on that if somebody knows whats exactly happening here.
My code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<!--<link rel="stylesheet" type="text/css" media="screen" href="main.css" />-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<script type="text/javascript">
function makeRequest(q) {
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 3
});
request.execute(function(response) {
$('#results').empty();
var resultItems = response.result.items;
$.each(resultItems, function(index, item) {
vidTitle = item.snippet.title;
vidThumburl = item.snippet.thumbnails.default.url;
vidThumbimg = '<pre><img id="thumb" src="'+vidThumburl+'" alt="No Image Available." style="width:204px;height:128px"></pre>';
$('#results').append('<pre>' + vidTitle + vidThumbimg + '</pre>');
});
});
}
function init() {
gapi.client.setApiKey('AIzaSyCWzGO9Vo1eYOW4R4ooPdoFLmNk6zkc0Jw');
gapi.client.load('youtube', 'v3', function() {
data = jQuery.parseJSON( '{ "data": [{"name":"orsons"}] }' );
$.each(data["data"], function(index, value) {
makeRequest(value["name"]);
});
});
}
</script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=init"></script>
</head>
<body>
<h1>YouTube API 3.0 Test</h1>
<ul id="results"></ul>
</body>
</html>
In addition to all the answers which explain that you must specify and provide a callback function for the Google API client <script> loading line, I'd like to point out that it seems that the onload parameter will never run the specified function (at least in Chrome) when you load the Google API client.js from a local file (even though you are serving the HTML page via a webserver and not loading it from the file-system, which apparently seemed to be the only gotcha with the Google API JS client...).
e.g.:
<script src="/lib/js/client.js?onload=handleClientLoad"></script>
Although client.js will be loaded, this will never launch the handleClientLoad function when it's finished loading. I thought it would be useful to point this out, as this was a really frustrating thing to debug.
Hope this helps.
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
This MUST be called at the end, or at least after you define your method "handleClientLoad". This is its callback, and only after it was called - it means google api is ready. This is why you get gapi.client is null.
For the fun of it, you can use a timeout of a few seconds before using gapi.client and see it is not null anymore.

Exception: missing } in XML expression

I am getting this error Exception: missing } in XML expression and also when i open my html file in FIREFOX and use Firebug 1.9.2, this error appear:
WL is not defined [Break On This Error]
WL.Event.subscribe("auth.login", onLogin);`
Here is my code:
<html><head>
<title>Greeting the User Test page</title>
<script src="js.live.net/v5.0/wl.js" type="text/javascript"></script>
<script type="text/javascript">
var APPLICATION_CLIENT_ID = "id",
REDIRECT_URL = "url";
WL.Event.subscribe("auth.login", onLogin);
WL.init({
client_id: APPLICATION_CLIENT_ID,
redirect_uri: REDIRECT_URL,
scope: "wl.signin",
response_type: "token"
});
WL.ui({
name: "signin",
element: "signInButton",
brand: "skydrive",
type: "connect"
});
function greetUser(session) {
var strGreeting = "";
WL.api(
{
path: "me",
method: "GET"
},
function (response) {
if (!response.error) {
strGreeting = "Hi, " + response.first_name + "!";
document.getElementById("greeting").innerHTML = strGreeting;
}
});
}
function onLogin() {
var session = WL.getSession();
if (session) {
greetUser(session);
}
}
</script>
</head>
<body>
<p>Connect to display a welcome greeting.</p>
<div id="greeting"></div>
<div id="signInButton"></div>
</body>
</html>
I dont know where is mistake, i just copy this sample code from skydrive api tutorial.
Of course, that I id and url strings replace with strings of my personal app.
Thanks for answers.
You need to include the Javascript file from the Microsoft server:
<script src="http://js.live.net/v5.0/wl.js" type="text/javascript"></script>
Your first <script> tag should look like:
<script src="http://js.live.net/v5.0/wl.js" type="text/javascript"></script>
or possibly
<script src="//js.live.net/v5.0/wl.js" type="text/javascript"></script>
if that site is configured properly. Without that, your URL was interpreted as being relative to the URL of your page.

Categories

Resources