CORS error with window.fetch on YouTube resource - javascript

I'm using window.fetch to retrieve a YouTube resource with the following URL:
http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=[id]&format=json
Using Fiddler, I see that I am getting the expected reply from YouTube's servers containing JSON data. However, I'm not able to use it as I'm getting a Javascript error.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:60366' is therefore not allowed
access.
I tried enabling CORS on my window.fetch but I read that this will only work if the server allows CORS in its header response. YouTube doesn't have this header field in its reply.
How do I enable my script to accept a response from YouTube using window.fetch? (I'm using Chrome v44.)
window.fetch(
url, {
method: 'GET',
mode: 'cors',
headers: {
'Accept': 'text/plain',
'Content-Type': 'text/plain'
}
})
...

I think you need to use youtube API to be able to make CORS request.
https://developers.google.com/youtube/v3/

Related

Can not post request in HTML JS | No 'Access-Control-Allow-Origin' header is present on the requested resource

I'm making a Java Compiler website for myself and I'm using JDoodle
In the document of this API, shows NodeJS code execute function
(https://docs.jdoodle.com/integrating-compiler-ide-to-your-application/compiler-api)
and I'm using javascript in html so I change a little bit to
// using jQuery
$.ajax({
url,
type: 'post',
data,
headers: {
'Content-Type': 'application/json'
},
dataType: 'json',
success: function(data) {
console.log(data);
}
})
but it gave me this error
Access to XMLHttpRequest at 'https://stage.jdoodle.com/execute' from origin has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I also tried $.post and Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not? but still the same.
Thank you!!
You need to enable header on the server side.
This has been asked before Enable CORS in fetch api
Alternatively you can ignore CORS with a flag.

Access-Control-Allow-Origin: * is not working when doing axios post in React

I am trying to post an object to API. However, I am getting the following error:
Access to XMLHttpRequest at 'https://ciboservis.herokuapp.com/api/v1/filial/adm' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have read other questions and found out that I needed to include Access-Control-Allow-Origin: *. So, here is my code now:
axios
.post("https://ciboservis.herokuapp.com/api/v1/filial/adm", {testName: 'foo'}, {
headers: {
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
console.log(res);
})
.catch((err) => console.log(err));
However, I am still getting the same error
As mentioned by Pratik in the comment, you need to apply these headers from the server side, which is hosted on Heroku.
Or For development purposes, you can install a chrome plugin to bypass this issue, but a long-term and better solution is to add this header on the server side
You can try this plugin - CORS Bypass Extension

Access to fetch at <my-google-cloud-function> from origin 'https://www.reddit.com' has been blocked ... CORS

I am working on a Google Chrome extension to block a subset of images from posts in a user's Reddit feed based on some backend computer vision run in Python in Google Cloud Storage. The Python code takes a single argument (the URL of an image in Reddit), which is passed in JavaScript via:
const api_url = https://<my-google-chrome-url>
var curUrl = $(this).attr("src")
fetch(api_url,{
method: 'POST',
body: JSON.stringify(curUrl),
headers: {
'Content-Type': 'application/json'
},
})
.then(data => {console.log(data)})
When the extension's code runs, I get the following in the console:
Access to fetch at 'https://this-is-the-path-to-my-google-cloud-function' from origin 'https://www.reddit.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I have tried multiple solutions, enumerated below:
I have followed the instructions here, such that by using Google's gsutil, I am able to confirm the following to be true for the bucket that my function lives in: [{"maxAgeSeconds": 3600, "method": ["GET", "POST"], "origin": ["https://www.reddit.com"], "responseHeader": ["Content-Type"]}]. I have also tried having ["*"] as my origin, to no avail.
I have also tried using in my fetch, mode: no-cors with no success.
Any suggestions or solutions would be greatly appreciated!
For what you mention, the CORS error in this case seems to come from the Cloud Function.
In order to address this, you should configure CORS for the Cloud Function, not Cloud Storage.
CORS consists of the preflight request and the main request. In your function you should check for preflight request by checking if the request's method is OPTION and if so, respond the appropriate headers. Here is a sample:
def cors_enabled_function(request):
# For more information about CORS and CORS preflight requests, see
# https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
# for more information.
# Set CORS headers for the preflight request
if request.method == 'OPTIONS':
# Allows GET requests from any origin with the Content-Type
# header and caches preflight response for an 3600s
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600'
}
return ('', 204, headers)
# Set CORS headers for the main request
headers = {
'Access-Control-Allow-Origin': '*'
}
return ('Hello World!', 200, headers)
For more information, you can read the docs

From origin 'null' has been blocked by CORS policy. How to fix this?

What I'm doing is, after choosing a file it calls an API. If it's a success (valid file) it gives me the total price. If it's a falsely formatted file, it gives me the relevant error from the backend.
Now, when I choose a correct file it works perfectly. But when I use a wrong file - it doesn't give me the error but it gives me following errors.
When I make the API call I get a CORS error saying :
POST https://test.test.test.com/subs/v12/2Subs net::ERR_ABORTED 422 (Unprocurable Entity)
Access to fetch at 'https://test.test.test.com/subs/v12/2Subs' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
But I get this only when I upload a file with false format. When I use Moesif CORS everything works perfectly.
But when I do this without Moesif CORS I get above error only when I load an incorrect file.
I tried using mode: "no-cors" also, But it didn't help me to get rid of POST error I'm getting.
Token is coming to the page because I printed it at the page load and it printed.
Here is how API header looks like.
var res = fetch('https://test.test.test.com/subs/v12/2Subs', {
method: "POST", // POST
mode: "cors",
cache: "no-cache",
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin': '*',
'Accept': 'application/json',
'Authorization': localStorage.getItem("userToken")
},
redirect: "follow",
referrer: "no-referrer",

Setting authorization in native browser fetch

I'm coming across an issue where I can't seem to set the headers for a fetch request and I think I'm missing something
var init = {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer myKey'
}
};
return fetch(url, init).then(function(response){...
When the request is inspected in the network tab, I'm not seeing the headers get set and instead see
Access-Control-Request-Headers:accept, authorization, content-type
when I would expect to see
Authorization: Bearer myKey
Content-Type: application/json
Accept: application/json
I've also tried using the native Headers() with zero difference.
Am I missing something here?
I was having the same issue and took a bit of investigating this evening. The problem is cross-origin resource sharing / CORS. With Fetch it is the default and it makes things considerably more complex.
Unless Both the origin and destination are the same it is a cross-domain request, and these are only supported if the request is to a destination that supports CORS ( Cross-Origin Resource Sharing ). If it does not then it will not go through. You'll usually see an error like No 'Access-Control-Allow-Origin' header is present on the requested resource
This is why you can not do Authorization headers on non-CORS sites; see #5 and basic headers
https://fetch.spec.whatwg.org/#concept-headers-guard
https://fetch.spec.whatwg.org/#simple-header
FORBIDDEN HEADER NAMES:
https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name
https://fetch.spec.whatwg.org/#forbidden-header-name
And unfortunately, before you try the XMLHttpRequest route, the same applies:
This is the same with XMLHttpRequest:
https://www.w3.org/TR/XMLHttpRequest/#the-open()-method
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
http://arunranga.com/examples/access-control/credentialedRequest.html
Finally, your choices to move forward are:
1. JSONP
2. Write a proxy that is not in the browser
3. Put CORS on the destination server
This article sums it up nicely

Categories