fetch api cannot load, url scheme 'file' is not supported - javascript

i tried to use fetch on localhost, but it didn't work.
here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
fetch("hi.txt").then(function(response){
response.text().then(function(text){
alert(text)
})
})
</script>
</body>
</html>
hi.txt file is in same folder with the script file.
below error is shown in console:
index.html:12 Fetch API cannot load file:///C:/~~~~/hi.txt. URL scheme "file" is not supported.
(~~~) is path

Since your URL is relative (it's just "hi.txt"), it's resolved against the URL of the page the code is running in. In your case, that appears to be file:///something — that is, a file you've loaded directly from your file system, not by requesting it from a server. Chrome doesn't allow fetching from the file scheme. The file scheme's origin is null. The Chrome team's interpretation of the Same Origin Policy is that no origin, not even itself, should match null. (A reasonable interpretation in my view, but opinions can vary.)
When doing web development, you want to be working through a server process because pages loaded directly from the file system behave differently in several sometimes-subtle ways vs. pages loaded from servers.
There are a couple of ways to do that:
Use the features of your IDE, if you use one, and/or extensions to it. For instance, for VSCode there's the "live server" extension which makes it very easy to run your code from a minimal server.
Use an actual web server process running locally. There are simple ones that are easy to install.
Use one of various "quick start" scaffolding tools that set up simple projects for you, often via npm (and Node.js), with a command you can use to build and run the project locally in development mode.

hi you are running your file like this way
-you are right clicking on your html file-opening with it browser. This way you are telling to browser to open your html file from your file location where you have saved it.Check in Your browser url bar you will get something like this C:/xampp/htdocs/xyz.html so this is your local directory file system. so now you have to first start your sever such as xampp or whatever server you have installed and then you type this localhost/filename or /subfolder name and / file name if you have stored it in subfolder...and hit enter.inshort you have to query to a server like you does in php file calling.....

You can just create a local web server (XAMPP) and upload there your hi.txt file. If you did that, replace
fetch("hi.txt")
with
fetch("http://127.0.0.1/hi.txt")

Related

Unable to load a image , (action blocked by cors policy) while i have set cross-origin to anonymous

So, i am getting started with machine learning in javascript, and i wanted to see an image classifier model in action.
so as i try to load the image in the browser it dosent work.
this is the error i get:
Access to image at 'file:///F:/rishit/ml5/imagerecognition/bird.png' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
this is my index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ML-5</title>
<script src="https://unpkg.com/ml5#0.4.3/dist/ml5.min.js"></script>
</head>
<body>
<h1 style="text-align: center;" >Image classification</h1>
<img src="bird.png"
alt="bird" id ="bird" >
<script src="script.js"></script>
</body>
</html>
and this is my script.js
let img = document.getElementById('bird')
img.crossOrigin = 'Anonymous'
let classifier = ml5.imageClassifier('MobileNet',onLoad)
function onLoad(){
console.log('yay!,its Done')
}
classifier.classify(img).then(
(results)=>{console.log(results)}
)
this is my file structure
bird.png index.html script.js
Are you sure you are serving the image from the right folder? Access to image at 'file:///F:/rishit/ml5/imagerecognition/bird.png' from origin 'null'.
I don't think that you should add img.crossOrigin = 'Anonymous' or similar, most likely is something wrong with how you are serving your static files
The problem should persist only if you open index.html directly from file explorer. Because it's using file:// protocol.
When you host it, or use something like Live Server extension in Visual Studio Code (which I highly recommend), everything should work fine because then it will be using http:// protocol.
I do this for my webapp. Works from desktop as well as from web server only using html and javascript. Useful if you dont want to create a localhost on you pc.
Remove ALL the cross origin related code you have there. You wont need it.
In the img html element remove the bird filename and just make src=‘#’
Add a html input type=‘file’ tag and use that to import the image at the click of a button.
When you get your image this way, in javascript youll pass the image into a FileReader i.e var reader = FileReader; this is where you convert the image to a data or binary file. CORS accepts data files, but web browsers ‘same origin’ policy may still pose a problem, so...
If the image file is small enough use sessionStorage to save the file to the browser storage. If the file is larger than 2 to 5 MB just go the extra mile and save it to IndexedDB. With images its super fast to save and retrieve and worth the extra code.
Now retrieve the file from storage and ‘Boom!’ You can use the image anywhere and anyhow you like without cors interference! (Oh yeah, add it to your img tag to see).
Since youre into machine learning, i’m assuming youre familiar with all these html and javascript api’s. I use it extensively to manipulate images on canvas from the file system which is usually a CORS nightmare! If youre interested in some code examples let me know.

Javascript in different folder than HTML

I'm new to web development. I have issues with having files stored in different folders (for safety reasons). Here's the index page which returns an error
<head>
<script src="../scripts/script.js"></script>
</head>
<body>
<?php include "../php/page.php"; ?>
Other code here...
</body>
My file structure is as follows
www/
html/
index.php
scripts/
script.js
php/
page.php
I don't get why including php file works (row 5 in the example code provided) and including javascript doesn't (row 2). I guess you're interested about the error so here's what Google Chrome's console says
Failed to load resource: the server responded with a status of 404 (Not Found)
It also shows that link to the resource and it appears to look for my.server.address/scripts/script.js like it doesn't care the ../ part. Can someone explain this behaviour?
PHP resolves paths on the computer's file system.
Web browsers resolve paths on the URL.
Your HTTP server has http://my.server.address/ mapping to www/html on the file system.
So ../scripts/script.js goes up one level from / … to / (because that is the top), then down to /scripts then down to /scripts/script.js.
The browser asks the HTTP server for /scripts/script.js and it maps that to the file system — www/html/scripts/script.js and returns a 404 because that file doesn't exist there.
The browser can only read data that the web server will send to it, and by keeping the scripts directory outside of the document root you haven't make it available via the web server.
Change
<script src="../scripts/script.js"></script>
to
<script src="/scripts/script.js"></script>
And your folder structure should be:
www/html/index.php
www/html/scripts/script.js
www/html/php/page.php

Not allowed to load local resource: JSP

I want to download a simple file by a link in jsp, but this name have a Chinese characters. Here my simple code :
<%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Titre de la page</title>
</head>
<body>
My link
</body>
</html>
that gives an error in navigator console : Not allowed to load local resource.
Thank you for your help :)
The problem are not the characters is the fact that you are trying to access the local disk. Your code is executing in a browser, and, for security reasons, you cannot access the local disk of the machine on which the page is displayed. Not to mention that, if that would have been allowed, it will load something different on every machine it runs on :).
So, either you use relative path in your HREF, or full URLs.
Remember, when you specify a link it goes to the SERVER to get the resource, not from local machine on which the browser is running.
Do not import or load local resource in this format:
src="file://home/web-server/foo/bar.jpg"
Because modern browsers not allowed to load files on server disk.
I suggest that you tell your proxy server to server the dir
foo
as a static file dir which browsers can access via your proxy server. In NodeJS, it will be like (suggest this file in /home/web-server named app.js)
var express = require("express");
var app = express();
app.use(express.static(path.join(__dirname, 'foo')));
Now, in your html code, you can call
My link
Then, you will see browser access your file by
http://yourdomain.com/4.导轨安装板.PDF
which will work.

how to protect css files like this site

I use this site for web font. (This is a web font provider like google fonts)
I need protect my css and js file like this site.
when you see below html file this css load complete and page show correctly but you don't access css files.
What method this site uses for securing css files??
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>B Koodak test</title>
<link href='http://www.font-api.ir/css/B Koodak={font-api.ir}.css' rel='stylesheet'
type='text/css'>
<style>
.myclass{
font-family:B Koodak,'B Koodak',tahoma;
font-size:12px;
}
</style>
</head>
<body>
<div class="myclass">This Is Test Text.</div>
</body>
</html>
for example if use access this link:
http://www.font-api.ir/css/B Koodak={font-api.ir}.css
this content is in base64 in above file: (thanks #Barmar and #Cracker0dks)
Rk9OVC1BUEkuaXI6DQpTYWxhbSENCnNoYXlhZCBsYXplbSBiYXNoYWQgYmVkYW5pZCBrZSBjb3B5
IGthcmRhbiBrYXJlIGtob29iaSBuaXN0IQ0KbG90ZmFuIGZvbnRlIG1vcmVkZSBuYXphcmUga2hv
ZCByYSBheiBmb250LWFwaS5pciBlbnRla2hhYiBrb25pZC4NCg==
This is decoded content. This is a message that say please no copy my css file (in persian language):
FONT-API.ir:
Salam!
shayad lazem bashad bedanid ke copy kardan kare khoobi nist!
lotfan fonte morede nazare khod ra az font-api.ir entekhab konid.
This is my chrome developer tools image:
Network tab, Request header and response:
The site that you pointed out is using the HTTP "Referrer" header to protect its css files. However, it is very simple bypass this protection (e.g. by faking the http header or sniffing browser traffic). If you insist on applying the same kind of check on your side you have to do it through a configuration on your web server.
If you are using Apache web server you can do it via .htaccess:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(css)$ - [NC,F,L]
Here is an online tool you can use to generate your htaccess for css files:
http://www.htaccesstools.com/hotlink-protection/
Ideally...it is not possible to protect images, css js or anything because when the browser loads a website, then it has to load all these elements too.....and if the browser is able to load it then any one can see/download the assets of the site.
Only possible things is to fake the stuffs for world using .htaccess write.
As for the site you referenced, the are using http.setRequestHeader to simply fool you....nothing is concrete...if you want to still access their stuffs, just do a little bit of googling and you'll yourself understand the difference!! :)
their css files are accessible. I know of no way to 'protect' since the browser downloads it.
follow these steps to view all css files:
1.in chrome, open dev tools (f12)
2.click cntr+o
enter '.css'
you now see all css files
EDIT in response to comment:
you are referring to just one part of the css: the #font-face import. by not usable, you mean that when you try to import this font, its not accessible? if so, they may be restricting responses to http requests to the url of the font: http://www.font-api.ir/fontsdir/35.eot?#'
the server at http://www.font-api.ir can filter its responses based on what domain is requesting the resource.
They Using .htaccess file to hide or secure file / directory. HTACCESS is a powerful file that can manipulate user control even access right.

running .bat file with javascript on html

I need to run a .bat file when the user clicks a link on the webpage. The .bat file basically runs another executable file and saves its output in a text file. So what I want is to create that text file once the user clicks the link to the .bat file on the webpage. Now, my .bat file is working perfectly when I execute it separately it creates the text file with contents, but somehow when I click the link it creates an empty text file. I looked at all the paths, they are all good;
I am using
Batch File ,
I have also tried
function runApp(which)
{ WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run (which,1,true);
}
But both of them just create the text file, and not put the contents
Does any one has any idea about this, also is there any other way to do this, like running the original .bat file and then getting its output in a text file directly with html/javascript?
Appriciate any help
Thanks
You don't say anything about what environment you are working with and I would guess you're not working with a server-side environment. JavaScript normally works in a browser to respond to the user's clicks and mouse moves etc but strictly within the confines of the browser. What you are trying to do is perform I/O operations on the underlying OS that the browser is running in (if you are running locally) or on the server-side OS in a normal webpage environment. It's not just a security issue - JavaScript simply doesn't have any direct connection to the client's OS or the server-side OS for that matter.
What you need is a web server environment like Apache or IIS etc, probably running an environment like ASP.NET, JSP, PHP(with a nice framework like CodeIgniter), or, rather you than me, CGI.
The user clicks a link or a submit button, and sends a request to the server. The relevant server-side program processes the request, runs the I/O operation you talk about and responds with the text. JavaScript is irrelevant in most of that process. It only comes into its own again when you are trying to figure out how to display the response in some fancy dynamic way.
There are millions of tutorials out there:
Tomcat (Java) http://wiki.apache.org/tomcat/GettingStarted
.NET(C# or VB) http://www.asp.net/get-started
Codeigniter (PHP) http://codeigniter.com/
CGI (not for the faint-hearted) http://www.cgi101.com/book/ch1/text.html
Having said all that, there is a server-side JavaScript environment (http://nodejs.org/) but the point is you will always be restricted by the limitations of the http protocol which means that you send a request to a server, the server processes your request depending on your privileges as a client, performing an I/O operation if appropriate, and responds with a stream of HTML. It does not allow direct operations on the server.
None of this is easy. Expect steep learning curves.
Displaying the text file contents
Here's a sample JSP page which will read the contents of a text file then display it on the webpage. I haven't added any buttons or anything - it just demonstrates how to read a file on the server:
<%#page contentType="text/html" pageEncoding="UTF-8" import="java.io.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>BufferedReader</title>
</head>
<body>
<%
String path = this.getServletContext().getRealPath("/target/message.txt");
File file = new File(path);
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
while(br.ready()){
out.print(br.readLine() + "<BR>");
}
reader.close();
%>
</body>
</html>
/target/message.txt is the virtual absolute path (from the root of the webapp). The call to getRealPath is the way you get a real physical path that allows you to create a File object.
I'll have a look later at using exec to run a batch file, but now you're thinking of a powerful language/library like Java why do you want to run a batch file? Wouldn't it make sense to write the program in Java?
use child_process.spawn of node.js

Categories