Saturday 17 August 2019

javascript - XMLHttpRequest cannot load file:




I have problem receiving data from api with all other links it was ok but that one is so hard .. So here is the code




$.ajax({
url: 'proxy.php?url=https://na.api.pvp.net/observer-mode/rest/consumer/getSpectatorGameInfo/NA1/26667724?api_key=xxxx',
dataType:"json",
success: function() {
alert("Success");
},
error: function() {
console.log("Error")
}

});


And this is the php code that i am using .



    header("Content-Type: text/javascript; charset=utf-8");
if (!isset($_GET['url'])) {
die();
}

$url = urldecode($_GET['url']);
$url = 'https://' . str_replace('https://', '', $url);
echo file_get_contents($url);
?>


On the console log is displayed --->XMLHttpRequest cannot load file:///D:/Install/xampp/htdocs/allInOne/proxy.php?url=https://na.api.pvp.n…pectatorGameInfo/NA1/26667724?api_key=xxx. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.send @ jquery-1.11.3.js:9664jQuery.extend.ajax @ jquery-1.11.3.js:9215jQuery.(anonymous function) @ jquery-1.11.3.js:9361jQuery.extend.getJSON @ jquery-1.11.3.js:9344renderInfo @ render.js:89onclick @ index.html:15
render.js:85 Error


Answer



Looks like the error is in the proxy.php file, it cannot use file_get_contents because the url returns 404.




and the php echoes




Warning: file_get_contents(https://euw.api.pvp.net/observer-mode/rest/consumer/getSpectatorGameInfo/EUW1/19496550?api_key=xxxx): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
in C:\xampp\htdocs\test\proxy.php on line 8


and when the javascript tries to read the response it fails.




Maybe this url is wrong?
https://euw.api.pvp.net/observer-mode/rest/consumer/getSpectatorGameInfo/EUW1/19496550?api_keyxxx
EDIT



remove



headers:{"Access-Control-Allow-Origin:": "*",
'Access-Control-Allow-Headers':"X-Requested-With",},
crossDomain: true,



and change



dataType:"jsonp",


to



dataType:"json",



crossdomain requests only needed in javascript, when you are requesting data from a url with Php this rule wont be needed



EDIT2
The porblem was loading the html file directly be clicking, thus making it give the error for the cross origin policy.
Fixed by address the file from xamp


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...