I have a tiny HTML/CSS/JS app I use to read and play certain types of files. I have no need for it to be on a server.
As of yesterday, it "worked." Suddenly, today I'm getting an error about using fetch with local files. I did make some settings changes on my Windows 10 laptop.
abcjs-init.js:15 Fetch API cannot load file:///E:/OneDrive/Documents/ABCJS-Minimal-Editor-Notation-Player/tunes/tune_list.txt. URL scheme "file" is not supported.
This is my code:
fetch(tunes_list_path, {mode: 'no-cors'})
.then(response =>
{
console.log("response:", response);
return response
})
.then(data =>
{
console.log("data:", data)
return data.text()
})
.then(Normal =>
{
console.log("got tunelist");
console.log("tune_list");
let tune_list = Normal.split("\n").sort();
addTunesToSelector(tune_list);
})
.catch(err =>
{
console.log('Fetch problem show: ' + err.message);
});
Further up is: let tunes_list_path = "tunes/tune_list.txt";.
The index.html loads fine. I can also view the file in the error directly with its URL. So it is visible to the browser.
Do I need to enable something in my browser? Add something to the fetch call?
Aha! I had changed a setting in Firefox that allowed COORS with local files: privacy.file_unique_origin.
I apparently erased that setting during my OS maintenance.
This solution is only for FF. There may be an equivalent setting for Chromium-based browsers.
Related
When using the service worker below, the behaviour is inkonsistent accross devices - unfortunately, just one of them is desired so far...
When I load the website in a normal browser tab (not via installed app) and simulate offline in the Chrome DevTools it actually loads everything from cache as excepted (html, css, js) and looks like this:
On a PC, when I launch the installed web app, simulate offline mode and reload the page, I see the following:
When I do the same on a mobile device and launch the installed web app the second time offline, it loads the HTML only without css/js.
How can I fix my service worker such that the outcome is always like in the first case?
self.addEventListener('fetch', event => {
if(event.request.method !== 'GET')
return;
function versionedURL(request){
switch(request.destination){
case 'image':
case 'script':
case 'style':
let
version = self.serviceWorker.scriptURL.split('?')[1]
;
return new Request(request.url + '?' + version);
default:
return request;
}
}
let
request = event.request.url.startsWith('https://matchflix.ch/') ? versionedURL(event.request) : event.request
;
event.respondWith(caches.open('matchflix')
.then(cache => fetch(request)
.then(response => {
cache.put(request, response.clone());
return response;
})
.catch(() => cache.match(request))
)
);
});
There was a mixup with the www and non-www version. After redirecting everything to the non-www version, it works now properly on every device.
I'm following the documentation for the Node.JS implementation of the IBM Watson Text-to-Speech API.
I want to output the resultant file into MP3 format. The documentation recommends augmenting the base code but I'm not sure how to do that. My code is rendering unplayable MP3s.
Here is what it says in the documentation:
textToSpeech.synthesize(synthesizeParams)
.then(response => {
// The following line is necessary only for
// wav formats; otherwise, `response.result`
// can be directly piped to a file.
return textToSpeech.repairWavHeaderStream(response.result);
})
.then(buffer => {
fs.writeFileSync('hello_world.wav', buffer);
})
.catch(err => {
console.log('error:', err);
});
As it says, response.result should be directly piped to a file. This is one of my many attempts (that renders an error).
textToSpeech
.synthesize(synthesizeParams)
.then(response => {
fs.writeFileSync('Hello.mp3', response.result)
})
.catch(err => {
console.log('error:', err)
})
How can I output the text-to-speech input as an MP3?
Provided your params are requesting an mp3 file, this will be the accept parameter, then your code looks ok. So if the output file isn't being recognised as an audio, then it is most likely a text file containing an error message. This error message will indicate what is wrong, which most likely will be an unauthorised message.
I take it that your catch error block isn't logging anything.
I have a problem with fetch data. My friend creates Rest Api.
There is my fun:
const AnyCors = `https://cors-anywhere.herokuapp.com/`;
const urlAllBus = `http://207.185.72.111:15430/stops?size=15`;
fetchBusStop = () => {
return new Promise((resolve, rejects) => {
fetch(AnyCors+urlAllBus)
.then((result) => {
if (!result.ok) throw result.json();
return result.json();
})
.then((result) => {
console.log(result);
resolve(result);
})
.catch((error) =>
error.then((body) => {
console.log('Bad', body);
rejects(body);
}),
);
});
};
I create an app with react-native. When I use only urlAllBus my virtual machine work fine. The problem is with a physical machine. When I try using my fun with urlAllbus in chrome I get a problem with CORS so I used AnyCors+urlAllBus and everything works fine. But in the virtual and physical machine there solutions not work. I don't know what I should do
You friend's API should accept CORS by adding a Access-Control-Allow-Origin: * header to its responses to allow any website to access it. They can also limit access to a specific site by setting the header to the base URL of such site, like Access-Control-Allow-Origin: http://example.com.
If the API is express-based, I hightly recommend the cors package for the job, as it makes it a single-line change.
Otherwise, tell them to give this MDN page a read for more information about CORS :)
I created simple web page using react and express. One module contains simple form with text input field, email input field and submit button and on submit it should send the mail to me, containing data from input fields. I used nodemail to create this sending mail thing! Luckily it works on chrome, unluckily it doesnt work on other browsers( firefox, IE, chrome on mobile ).
I found out that the problem is not in the backend side, but in the function connecting frontend with backend, but after that I got stuck and dont know what to do :(
onSubmit = e => {
var newMessage = {
msg_sender: this.state.msg_sender,
msg_content: this.state.msg_content
}
axios.post("http://localhost:4000/message", newMessage)
.then(res => console.log(res.data))
.catch(err => console.log("Error! " + err)
);
};
That is the part connecting frontend with backend - as I said, it works fine in chrome, but doesnt in other browsers.
Arrows functions are still a relatively new feature in JavaScript and unfortunately some browsers are still not up-to-date and likely never will be able to support them (Looking at you Internet Explorer).
There's a couple of ways to work around this.
1) You could rework all your arrow functions into standard functions:
onSubmit = function(e){
var newMessage = {
msg_sender: this.state.msg_sender,
msg_content: this.state.msg_content
}
var axiosSetup = axios.create({
baseURL: "http://localhost:4000"
})
axiosSetup.post("/message", newMessage)
.then(function(res){ console.log(res.data) })
.catch(function(err){ console.log("Error! " + err) })
);
};
2) You can integrate Babel in your application, which is a compiler that converts your javascript into compatible code for all browsers:
https://babeljs.io/
If you're building application for browser-compatibility it will also be in your best interest to check out mozilla's web developer guide which is a great reference to check if your code will work on other browsers.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Alternatively, you can also use JavaScript's native fetch API. The benefit being that you do not have to install any libraries and its setup for use will be the same across all browsers
onSubmit = function(e){
var newMessage = {
msg_sender: this.state.msg_sender,
msg_content: this.state.msg_content
}
fetch('http://localhost:4000/message', {
method: 'POST',
body: newMessage
})
.then(function(res){ console.log(res.json()) })
.catch(function(err){ console.log("Error! " + err) })
};
See documentation here:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
I have a pdf file that is generated from server and I would like to allow the user to share this file via navigator.share. Is it possible to share a file instead of URL?
navigator.share({
title: 'Web Fundamentals',
text: 'Check out Web Fundamentals — it rocks!',
url: 'https://developers.google.com/web',
})
.then(() => console.log('Successful share'))
.catch((error) => console.log('Error sharing', error));
Chrome 93.0.4570.0 now supports sharing PDF files with Web Share. See https://chromiumdash.appspot.com/commit/7d30d42a018d4aa76fca2896f2903d892b5f5284 and https://bugs.chromium.org/p/chromium/issues/detail?id=1006055
shareButton.onclick = async () => {
const response = await fetch("https://example.com/files/hello.pdf");
const buffer = await response.arrayBuffer();
const pdf = new File([buffer], "hello.pdf", { type: "application/pdf" });
const files = [pdf];
// Share PDF file if supported.
if (navigator.canShare({ files })) await navigator.share({ files });
};
Chrome for Android (75+) now supports this feature (called Web Share API Level 2) and hopefully other browsers will follow suit soon.
A demo is available here.
If you want to share your pdf file, I will suggest that you provide them as direct links to url property. Note that a url of '' refers to the current page URL, just as it would in a link. Any other absolute or relative URL can also be used.