read file from computer javascript and print console.log its not print - javascript

when i debug this code in to chrome console then its not show any output or alert! please help me to complete this code! i need to get read my read.txt file text in to console.log....
the code was i try one is shows below.
function loadText() {
fetch('C:\Windows\Temp\read.txt')
.then(function(response){
return response.text();
})
.then(function(data){
console.log(data);
alert(data)
})
.catch(function(error){
console.log(error);
alert(data)
})
}

Try below code and indicate your directory like below
async function fetchText() {
let response = await fetch('../demo.txt');
console.log(response.status); // 200
console.log(response.statusText); // OK
if (response.status === 200) {
let data = await response.text();
console.log(data);
// handle data
}
}
fetchText();

This seems like a duplicate of this issue - AJAX request to local file system not working in Chrome?
The problems are the same, however you are using the fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) not an XMLHttp request (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)
When i run loadText i get the following error:-
Fetch API cannot load . URL scheme must be "http" or "https" for CORS request.
You cannot make requests to the filesystem in Chrome. However you can disable Chrome security using flags (--allow-file-access-from-files)
see - Allow Google Chrome to use XMLHttpRequest to load a URL from a local file however this is not advised.
You will also need to update your path in the fetch function by prefixing with file:/// this tells it to look in the file system, and changed the protocol from http or https.

Related

Cannot get simple weather feteching code to work

I'm using the following code
try {
const response = await fetch(endpoint);
if(response.ok) {
jsonResponse = await response.json();
return jsonResponse;
}
} catch(error) {
console.log(error.message);
}
to fetch weather info from openweathermap. When I run the program locally on my computer or using a local server with VSC I get a "NetworkError when attempting to fetch resource." error caught. When I input the URL (https://api.openweathermap.org/data/2.5/weather?q=Madrid&appid=...)straight into the web browser it shows me the content without any issues. I can't for the life of me figure out what I'm doing wrong. What am I missing? (the link is missing the api key for obvious reasons, but it's written correctly in the code)

How to fetch data from an API from GSX2JSON?

So I have this link I generated with GSX2JSON, and it looks like this: http://gsx2json.com/api?id=136PcbZppJfCH1vbE_j4X803umxv0_EWEg5Tjxnvvp7o&sheet=1. Now, I want to fetch the data into a variable, and so I used this code:
async function deetdeet(){
let response = await fetch('http://gsx2json.com/api?id=136PcbZppJfCH1vbE_j4X803umxv0_EWEg5Tjxnvvp7o&sheet=1');
if (response.ok) {
let json = await response.json();
console.log(json)
console.log("hyeet")
} else {
alert("Err: " + response.status);
}
}
deetdeet()
Sadly, this doesn't seem to return the JSON that is shown in the API, and I can't figure out why. I've tried using fetch() and even .getJSON() from JQUERY all to no avail. Is there an issue with my code, or the API I'm using?
Browsers block mixed content to protect against various attacks on users, so fetching HTTP resources from a HTTPS context will be blocked.
Look into proxying your request with a HTTPS API-Wrapper or using an API supporting HTTPS.
Make sure if you are running your site off HTTPS, that all fetch() requests are being handled through HTTPS as well.

Retrieved JavaScript file from cache api not executing

In an web pure vanilla JavaScript app that does not use service workers, I would like to explicitly cache a JavaScript file that is sitting on an AWS S3 file server. The following script would be sitting in the index.html file for the application (I’ve modified the URL as it's a client project):
<script>
caches.match('https://s3.amazonaws.com/com.myproject/myjavascript.js')
.then(function(response) {
if (response) {
return response;
} else {
fetch('https://s3.amazonaws.com/com.myproject/myjavascript.js')
.then(function(res) {
return caches.open('mycache')
.then(function(cache) {
cache.put('https://s3.amazonaws.com/com.myproject/myjavascript.js',res.clone());
console.log(res.clone());
return res;
});
});
}
});
</script>
I believe this code should do the following: Check if the myjavascript.js file is in the cache. If it is, return the JavaScript file which would then be executed by the browser. If myjavascriptfile.js is not found in the cache, it will be fetched and placed in the subcache ‘mycache’ and finally returned to the browser where it would be executed.
After running this, I find the URL for the file in the cache with a response of “Ok”, but the code is not executed by the browser and I don’t see the file contents in sources within the Chrome browser developer tools.
Why would this not be working? What is wrong with my thinking on this.
Many thanks,
Fred
fetch by itself will not execute JavaScript. It simply makes a request for the specified content and make it available for the code to access. If you really want to continue with this approach it is possible to take the text and eval it.
const url = 'https://unpkg.com/underscore#1.8.3/underscore-min.js';
caches.match(url)
.then(function(response) {
if (response) {
return response;
} else {
return fetch(url)
.then(function(res) {
return caches.open('mycache')
.then(function(cache) {
cache.put(url,res.clone());
console.log(res.clone());
return res;
});
});
}
})
.then(function(response) {
console.log(response);
response.text().then(function(text) {
eval(text);
console.log(_);
});
});
Note: Why is using the JavaScript eval function a bad idea?
The code sample you have is a pattern commonly found in Service Workers. The reason it works in that context is the initial request is from <script> tags and not direction invocation of fetch. Because of the <script> tag the browser handles automatically executing the returned content.
<script src="https://unpkg.com/underscore#1.8.3/underscore-min.js"></script>

Javascript weird Fetch() issues, fails on a specific JSON data/format

I have the following code using fetch
var url1 = 'http://jsonplaceholder.typicode.com/users';
var url2 = 'http://teaconcepts.net/temp/api_test.php';
fetch(url1)
.then(function (result){
console.log("Result received");
return result.json();
}).then(function(data){
// console.log("data received",data[1]['name']);
console.log("data received",data);
}).catch(function(error){
console.log("Error in Fetch",error.message);
});
I'm fetching valid JSON data from both URLs, but with slightly different structure
var url1 = 'http://jsonplaceholder.typicode.com/users';
var url2 = 'http://teaconcepts.net/temp/api_test.php';
If I load data from URL1, things are fine. But if I load url2 i get an error "Failed to fetch"
What gives???
See demo: http://jsbin.com/yaxecewopu/1/edit?js,console
The issue here is the same-origin policy. If you run this JavaScript on http://teaconcepts.net it will work. Or, you can get teaconcepts.net to respond with an Access-Control-Allow-Origin header to allow any origin or specific origins (such as jsbin.com and stackoverflow.com)
Here issue with second url is encoding problem, check second url here
Paste your url in
https://jsonformatter.curiousconcept.com/ and check what is issue with return type of json. or else see below image result of second url json
if you author for that php file see the below thread to solve issue php returns invalid json
The second URL refers to a site that doesn't allow cross-origin requests. The browser therefore disallows access via fetch() or XMLHttpRequest.

How do I get source code from a webpage?

How can we get the source code of a webpage from a webpage in php and/or javascript?
In Javascript without using unnecessary frameworks (in the example api.codetabs.com is a proxy to bypass Cross-Origin Resource Sharing):
fetch('https://api.codetabs.com/v1/proxy?quest=google.com').then((response) => response.text()).then((text) => console.log(text));
Thanks to:
#PLB
#Shadow Wizard
Getting the source code of an iframe
http://www.frihost.com/forums/vt-32602.html
#Matt Coughlin.
First, you must know that you will never be able to get the source code of a page that is not on the same domain as your page in javascript. (See http://en.wikipedia.org/wiki/Same_origin_policy).
In PHP, this is how you do it :
file_get_contents($theUrl);
In javascript, there is three ways :
Firstly, by XMLHttpRequest : http://jsfiddle.net/635YY/1/
var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);
Secondly, by iFrames : http://jsfiddle.net/XYjuX/1/
var url="../XYjuX";//Remember, same domain
var iframe=document.createElement("iframe");
iframe.onload=function()
{
alert(iframe.contentWindow.document.body.innerHTML);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);
Thirdly, by jQuery : http://jsfiddle.net/edggD/2/
$.get('../edggD',function(data)//Remember, same domain
{
alert(data);
});
Following Google's guide on fetch() and using the D.Snap answer, you would have something like this:
fetch('https://api.codetabs.com/v1/proxy?quest=URL_you_want_to_fetch')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.text().then(function(data) {
// data contains all the plain html of the url you previously set,
// you can use it as you want, it is typeof string
console.log(data)
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
This way you are using a CORS Proxy, in this example it is Codetabs CORS Proxy.
A CORS Proxy allows you to fetch resources that are not in your same domain, thus avoiding the Same-Origin policies blocking your requests.
You can take a look at other CORS Proxys:
https://nordicapis.com/10-free-to-use-cors-proxies/
Ajax example using jQuery:
// Display the source code of a web page in a pre tag (escaping the HTML).
// Only works if the page is on the same domain.
$.get('page.html', function(data) {
$('pre').text(data);
});
If you just want access to the source code, the data parameter in the above code contains the raw HTML source code.

Categories