Firefox is blocking fetch requests on same origin - javascript

I'm a little stumped with this one, I'm making a request in firefox to a relative url:
await fetch('/foo/bar',{});
This errors out with:
TypeError: NetworkError when attempting to fetch resource.
Furthermore, the urls show up as 'blocked' in the network tab:
Things I've checked:
uBlock origin is off
Tracking protection is off
Server is running, the request succeeds when I directly open it in my browser, or via CURL.
This is not related to CORS, as the origins are all local.

I figured out the issue.
The fetch() request was initiated.
An unrelated error was thrown.
This error was not checked correctly, causing the browser to redirect to a different url.
This redirect caused the (still running) fetch request to abort.
The aborted request shows up as a block, setting me on an incorrect path to try and fix this.
So things were broken, just not where I expected. Thank you for helping me think and find the root cause

Related

(CORS) - Cross-Origin Resource Sharing connection issue

I am currently in the process of creating a browser extension for a university project. However as I was writing down the extension I hit a really weird problem. To understand fully my situation I will need to describe it in debt from where my issue comes.
The extension that I am currently working on has to have a feature that checks if the browser can connect to the internet or not. That is why I decided to create a very simple AJAX request function and depending on the result returned by this function to determine if the user has internet connection or not.
That is why I created this very simple AJAX function that you can see bellow this line.
$.ajax({
url: "https://enable-cors.org/index.html",
crossDomain: true,
}).done(function() {
console.log("The link is active");
}).fail(function() {
console.log("Please try again later.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So far, as long as I understand what it is doing, it is working fine. For example, if you run the function as it is, it will succsesfully connect to the url and process with the ".done(function..." if you change the url to "index273.index" a file which does not exist it will process with the ".fail(function...". I was happy with the result until I decided to test it further more and unpluged my cable out of my computer. Then when I launched the extension it returned the last result from when the browser had connection with the internet. My explanation why the function is doing this is because it is caching the url result and if it cannot connect it gives the last cached value. My next step to try and solve this was to add "cache: false" after the "crossDomain: true" property but after that when I launch the extension it gives the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://enable-cors.org/index?_=1538599523573. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
If someone can help me out sorting this problem I would be extremely grateful. I would want to apologise in advance for my English but this is not my native language.
PS: I am trying to implement this function in the popup menu, not into the "content_scripts" category. I am currently testing this under Firefox v62.0.3 (the latest available version when I write this post).
Best regards,
George
Maybe instead of calling the URL to check if the internet connection is available you could try using Navigator object: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/connection
unless the remote server allowed origin (allowed cors) then you can't access it because it's a security issue.
But there are other things you can do:
You can load image and fire event when an image is loaded
You can access remote JSON via JSONP response
but you can't access other pages because (unless that server allows it) it's a security issue.

Service Worker failure - Redirected response while RedirectMode is not "follow"

Browser: Firefox 58.0.2 (64-bit)
I'm trying to write a very simple service worker to cache content for offline mode, following the guidance here and here.
When I load the page the first time, the service worker is installed properly. I can confirm it's running by looking in about:debugging#workers.
However, at this point if I attempt to refresh the page (whether online or offline), or navigate to any other page in the site, I get the following error:
The site at https://[my url] has experienced a network protocol
violation that cannot be repaired.
The page you are trying to view cannot be shown because an error in
the data transmission was detected.
Please contact the website owners to inform them of this problem.
The console shows this error:
Failed to load ‘https://[my url]’. A ServiceWorker passed a redirected Response to FetchEvent.respondWith() while RedirectMode is not ‘follow’.
In Chrome, I get this:
Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': Cannot construct a Request with a Request whose mode is 'navigate' and a non-empty RequestInit.
Per this thread, I added the { redirect: "follow" } parameter to the fetch() function, but to no avail.
(Yes I did manually uninstall the Service Worker from the about:debugging page after making the change.)
From what I understand, however, it's the response, not the fetch, that's causing the problem, right? And this is due to my server issuing a redirect when serving the requested content?
So how do I deal with redirects in the service worker? There are obviously going to be some, and I still want to cache the data.
Partly spun off from https://superuser.com/a/1388762/84988
I sometimes get the problem with Gmail with Waterfox 56.2.6 on FreeBSD-CURRENT. (Waterfox 56 was based on Firefox 56.0.2.) Sometimes when simply reloading the page; sometimes when loading the page in a restored session; and so on.
FetchEvent.respondWith() | MDN begins with an alert:
This is an experimental technology …
At a glance, the two bugs found by https://bugzilla.mozilla.org/buglist.cgi?quicksearch=FetchEvent.respondWith%28%29 are unrelated.
Across the Internet there are numerous reports, from users of Gmail with Firefox, of Corrupted Content Error, network protocol violation etc.. Found:
Mozilla bug 1495275 - Corrupted Content Error for gmail

CORS error, but data is fetched regardless

I have a generated React site I am hosting in an S3 bucket. One of my components attempts to fetch something when loaded:
require('isomorphic-fetch')
...
componentDidMount() {
fetch(`${url}`)
.then(res => {
console.log(res);
this.setState({
users: res
})
})
.catch(e => {
// do nothing
})
}
The url I am fetching is an AWS API Gateway. I have enabled CORS there, via the dropdown, with no changes to the default configuration.
In my console, for both the remote site and locally during development, I see:
"Failed to load url: No 'Access-Control-Allow-Origin' header is present on the requested resource." etc
However, in the Chrome Network tab, I can see the request and the response, with status 200, etc. In the console, my console.log and this.setState are never called, however.
I understand that CORS is a common pain point, and that many questions have touched on CORS. My question: Why does the response show no error in the Network tab, while simultaneously erroring in the console?
The fetch(`${url}`) call returns a promise that resolves with a Response object, and that Response object provides methods that resolve with text, JSON data, or a Blob.
So to get the data you want, you need to do something like this:
componentDidMount() {
fetch(`${url}`)
.then(res => res.text())
.then(text => {
console.log(text);
this.setState({
users: text
})
.catch(e => {
// do nothing
})
}
Failed to load url: No 'Access-Control-Allow-Origin' header is present on the requested resource." etc
That means the browser isn’t allowing your frontend code to access the response from the server, because the response doesn’t include the Access-Control-Allow-Origin header.
So in order for the above code to work, you’ll need to fix the server configuration on that server so that it sends the necessary Access-Control-Allow-Origin response header.
However, in the Chrome Network tab, I can see the request and the response, with status 200, etc. In the console, my console.log and this.setState are never called, however.
That’s expected in the case where the server doesn’t send the Access-Control-Allow-Origin response header. In that case, the browser still gets the response — and that’s why you can see it in the devtools Network tab — but just because the browser gets the response doesn’t mean it will expose the response to your frontend JavaScript code.
The browser will only let your code access the response if it includes the Access-Control-Allow-Origin response header; if the response doesn’t include that header, then the browser blocks your code from accessing it.
My question: Why does the response show no error in the Network tab, while simultaneously erroring in the console?
For the reason outlined above. The browser itself runs into no error in getting the response. But your code hits an error because it’s trying to access an res object that’s not there; the browser hasn’t created that res object, because the browser isn’t exposing the response to your code.
You may be seeing the status 200 for the OPTIONS not the GET. There is a setting for CORS to handle legacy, so it won't confuse your client. I had to do that last time in a React app. Your error is that your CORS isn't configured properly (sorry, obviously). Chrome won't let your client tlak to the backend if it doesn't get the headers properly. Other browsers probably also, probably React also. It may be some kind of HTTP protocol if only one side has CORS enabled. Someone can correct me there. It's a similar security consideration as sending a request to HTTP from HTTPS. Chrome blocks it.
It looks to me like it's your backend. CORS isn't active or it would put that header on, and after that, you would see errors about origin mismatch in the frontend client.
In my experience, it's a 2-3 step combo, make sure OPTIONS don't send confusing signals to your client (look for settings to do with 200). This is a config setting in your backend. Then, make sure the backend is configured to use CORS. You very specifically need to enter the origin hostname and port that the backend is to expect traffic from.
I could probably give better input if I see what languages and/or frameworks you are using besides React.
This is what you would do in Express JS and node for your Backend:
const cors = require('cors')
// note http or https
app.use(cors({
origin: 'http://example.com:1337',
//origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
optionsSuccessStatus: 200
// some legacy browsers (IE11, various SmartTVs) choke on 204
}))
My last React app was detonating without optionsSuccessStatus by throwing success when it was fail.
To give you a little bit of imagery to work with, CORS is simple but finicky. It's a simple matter of alignment. Once your backend is configured to a) use CORS and b) know who to accept traffic from, it's done. Once your frontend is configured to handle this traffic, it's done. It's like aligning a square peg in a round hole until you get the config settings aligned.
Try using Postman to send some GET requests to the Backend. You can observe the headers from there.

XMLHttpRequest cannot load - file footer.html, "Error: Failed to execute 'send' on 'XMLHttpRequest'

I have two of the same site. My 1st site is http://educationaboveall.org/ and the 2nd is http://www.savantgenius.com .
1st site is loading properly on every device without any error but the 2nd (www.savantgenius.com) site is not loading properly in mobile and table devices. It is only loading properly in desktop browser. I have also found 32 console error.
Are there any jQuery issues? And please tell me how to be able to fix it.
I'm getting the "XMLHttpRequest cannot load
file:///D:/Work%20File/My%20Work%20File/mY%20Work%20Backup/Sophie/Work%20File/footer.html.
Cross origin requests are only supported for HTTP." and "Error: Failed
to execute 'send' on 'XMLHttpRequest': Failed to load
'file:///D:/Work%20File/My%20Work%20File/mY%20Work%20Backup/Sophie/Work%20File/footer.html"
error, but I don't know what's causing it nor how to fix it.
Please see the screenshot - http://prntscr.com/4fm0d8
I Think that you should call it from a http webserver and not like simple file in browser. This mean request a file in a web server like http://localhost/XML/catalog.html not from file:///E:/Projects/XML/catalog.html.
It is as the message says:
cannot load file:///D:/Work%20File/My%20Work%20File/mY%20Work%20Backup/Sophie/Work%20File/footer.html. .
You are referencing to a file on a Windows boxes filesystem and not in a webservers folder.
Second: you have a CORS-issue (which in this case is caused by the filesystem reference)
Cross origin requests are only supported for HTTP
See MDN for more infos.
To solve the issue, you have to configure your webserver to allow such requests. Check your webservers manual.
I had the same problem with my InfluxDB connection and it turns out I did not prepend the URL settings in the datasource with 'http://'. This could be nicer in Grafana, e.g. mentioning there is no protocol defined for accessing the source.
In your case it's clear that you somehow configured Grafana to look for D:\, which is not accessible for your browser. So check your data source URL.

Why does this jQuery.ajax not raise an error?

We had an interesting issue this morning - the details of the issue itself aren't relevant here, and I already fixed it, but I did run into something strange, to me, about jQuery.
The site I am building internally runs on https, only, so Apache is set to redirect any inbound http request to its https equivalent. This redirect is working fine. But, I had a bug in my software where I was trying to send the following ajax request:
jQuery.ajax({ type: "PUT",
url: "http://somewhere.com/cmdt/todo_lists/8457/toggle",
data: { deployment_id: 827},
dataType: "script"});
I understand that this would fail - I'm alright with jQuery not wanting to follow a redirect. But the actual behaviour is even weirder: I never see an xhr request go out at all! And there's no javascript error! It just fails, silently. If I change the url to https, or to a relative path, it works fine, no problem. My question is, why wasn't it TRYING to send out the request before? And why didn't it raise an error?
The reason you're not getting a failure is because it's a cross-site request, and so instead of using XMLHttpRequest, it's actually generating an HTML <script> tag and dropping it into the DOM, and using that mechanism to load the file.
This works reasonably well (considering it's a complete hack around wrong-headed browser "security" notions) but there's no way for jQuery to trap errors at that point, sadly. You will likely get a browser error if you have developer mode turned on, but that's it.
If you run that from an url that's https and try to open the equivalent http page you run into cross domain problems due to the different protocols they use. Have a look at same origin policy.

Categories

Resources