If I inject a script programmatically like this:
((global, url) => {
let s = document.createElement('script')
s.src = url
global.document.body.appendChild(s)
})(window, 'https://example.com')
The request will go through just fine and the script will be inserted with the response to the request to "https://example.com" ... but if I try to make an explicit fetch request to the same URL I get a CORS error? Why is that happening?
CodePudding user response:
You just invented JSONP :D Description from w3school:
JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.
Here is explanation on stackoverflow