简体   繁体   中英

Getting this error when requesting data from API

I've been messing around with pulling data from API's but for some reason it gives me this error and I have no idea how to fix this:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://battlefieldtracker.com/bf1/api/Stats/DetailedStats?platform=2&personaId=376461834&displayName=TR_ISMAIL_TR&game=tunguska . (Reason: CORS header 'Access-Control-Allow-Origin' missing).

So I generated this url from http://docs.trnbattlefield.apiary.io/#introduction/parameters/platform and I can see my in-game stats from Battlefield 1 on that site but when I copy paste the url to the web, it gives me a bad request.

So does anyone know how to fix this?

If your using AJAX try setting the datatype to JSONP

$.ajax({
 url:"END POINT",
 dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
 success:function(json){       
     alert("Success");
 },
 error:function(){
     alert("Error");
 }      
});

You cannot make a cross-domain AJAX request if the server does not allow it (it is sometimes possible with "pre-flight" requests, explained in details here ).

What you can do , if you have control over your webserver, is to make a reverse proxy in order to access the remote data with a local URL.

Here is the way to do it with Apache (needs mod_proxy to be enabled):

< VirtualHost *:80 >
    ServerName www.yourserver.com
    ProxyPreserveHost On
    ProxyRequests On
    ProxyPass /bfapi/ https://battlefieldtracker.com/bf1/api/
    ProxyPassReverse /bfapi/ https://battlefieldtracker.com/bf1/api/
< /VirtualHost >

And if you use Nginx, place this in a server section of your config file:

location /bfapi/ {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_pass https://battlefieldtracker.com/bf1/api/;
}

That way you can call the API with the following URL: https://yourserver.com/bfapi/Stats/DetailedStats?platform=2&personaId=376461834&displayName=TR_ISMAIL_TR&game=tunguska

Of course, you have to replace yourserver.com with your own domain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM