Sending request to website using Javascript - javascript

i am trying to send an HTTP request to specific website and i am facing error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
say for instance that i want to send request to Google.com and receive the HTML response.
my code was written using JQUERY AJAX:
function sendRequest(URL) {
$.ajax({
type:'GET',
url:URL,
success:function(result){console.log(result);}
});
}

Maybe it can help you : https://cloud.google.com/storage/docs/cross-origin#Troubleshooting%20CORS-Related-Problems
Look this one also : Access-Control-Allow-Origin error sending a jQuery Post to Google API's

Related

Why does my API call work in chrome but not in my code?

I'm trying to call the Binance API to get the LTC price in BTC and I tested the link on my browser "https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC" How do i get the json file from that link into my javascript file?
$(document).ready(function() {
var url = 'https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC';
$.ajax( {
url: url,
dataType: 'jsonp',
type: 'GET',
success: function(data) {
console.log(data); //returns nothing
}
});
})
As mentioned in other answer, there is CORS issue. So you can try with proxyURL from client side as below,
$(document).ready(function() {
var url = 'https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC';
const proxyURL = "https://cors-anywhere.herokuapp.com/";
$.getJSON(proxyURL + url, function(playerData) {
console.log(playerData);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Hope it helps.
The request to https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC provides json data this uses CORS policy
{"symbol":"LTCBTC","price":"0.01520100"}
JSONP would look like
myCallback({"symbol":"LTCBTC","price":"0.01520100"})
This looks like and works like a Javascript / PHP function.
The URL for a jsonp includes a callback in the URL ... https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC&callback=myCallback
But is not supported on this site
{"code":-1101,"msg":"Too many parameters; expected '1' and received
'2'."}
It might be openable with php on your site? I can not test from the system I'm on I don't have socket transport "ssl" setup on my tablet to test.
Yes it works from a PHP wrapper.
myJSONP(<?php echo file_get_contents('https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC');?>);
If you check on console after change dataType: 'jsonp' to dataType: 'json', you will get the following as your code and their script not on same host and they need to enable Access-Control-Allow-Origin to access from other domain. You may use cur if you use php.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
While performing the request from your browser or postman or fiddler you will get the result
But while performing a request from the application you will be failed with error message
Access to XMLHttpRequest at 'https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The issue has to be fixed from your server side end.
Please refer
Cors understanding
Also, find the solution to the problem if you're using C# .Net as your backend
Solution for cors

Need help working with SMMRY API

I'm using http://smmry.com/api for a small project. I'm fairly new to AJAX and have trouble using it. Here's what I have so far:
var a = $.ajax({
type:'POST',
url:'http://api.smmry.com/&SM_API_KEY=XXXXXXXX',
headers: {'Authorization': '["Expect:"]'},
data: {'SM_URL':'https://en.wikipedia.org/wiki/Human%E2%80%93computer_interaction'},
contentType:'application/json',
dataType: 'json',
});
console.log(a);
The error I'm getting:
XMLHttpRequest cannot load http://api.smmry.com/&SM_API_KEY=XXXXXXXX. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I'm fairly sure it has something to do with headers. I have no idea what to do and would really appreciate it if someone could help me!
The error you are getting has to do with CORS. The XMLHttpRequest sends a preflight request, which is not supported by the SMMRY API, and is something that needs to be enabled server side. What can you do instead?
You can talk to their API through a server, e.g. a simple Node server.
You then send the XMLHttpRequest to your own server, where you do allow preflight request by allowing CORS (this is a simple line of code in a Node / Express server), and you forward the request to the SMMRY API and send the response back to your site. This process is called "proxying".

GET JSON with XMLHttpRequest

I have a python script which generates a JSON and I can see it in http://192.168.1.171:17000/
In the Network tab I get
200 GET / 192.168.1.171:17000 json transfereed 40KB
When I'm trying to GET it from another webpage with javascript
var url = "http://192.168.1.171:17000";
var Httpreq = new XMLHttpRequest();
function Get(url){
Httpreq.open("GET", url, false);
//Httpreq.setRequestHeader( 'Access-Control-Allow-Origin', '*');
Httpreq.send(null);
return Httpreq.responseText;
}
var json_obj = JSON.parse(Get(url));
console.log("data: "+json_obj);
in the network tab I get
200 GET / 192.168.1.171:17000 json transfereed 0KB
it's Response tab
SyntaxError:
JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
and in the console
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help http://xhr.spec.whatwg.org/
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.171:17000/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
NS_ERROR_FAILURE:
When I add
Httpreq.setRequestHeader( 'Access-Control-Allow-Origin', '*');
instead of fixing the problem I'm getting one more error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.171:17000/. (Reason: CORS request failed).
When I visit http://192.168.1.171:17000/ I'm getting my json, which is valid, and when I run my javascript code with another json it runs. But when I run my javascript code with my json it doesn't run. Could you please help me to understand what I'm doing wrong here?
That header needs to be added to the server's response, not the client's request. In other words, you need to modify your Python app to return the Access-Control-Allow-Origin header. (How exactly you do that depends on what you're using on the Python side.)

Ajax call using jsonp not working, "Uncaught SyntaxError: Unexpected token"

Problem
I'm working with a open data, city API for river levels, but when I make my ajax call using jsonp I receive an error for Uncaught SyntaxError: Unexpected token < which doesn't appear to be coming from my scripts.js
It is also my understanding that my ajax call might not be working because this API only spits out XML or json. I've tried to switch my dataType: json, but when I do that I receive the error below. Not particular sure if using jQuery's .getJSON is the best method to grab this data?
Data: http://opengov.brandon.ca/OpenDataService/opendata.html
Documentation: http://opengov.brandon.ca/api.aspx
Error (when switching dataType: json)
XMLHttpRequest cannot load http://opengov.brandon.ca/opendataservice/Default.aspx?date=riverlevel&columns=date&dataset=riverlevel. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
scripts.js
$(function(){
$.ajax({
url: 'http://opengov.brandon.ca/opendataservice/Default.aspx?date=riverlevel&columns=date&dataset=riverlevel',
type: 'GET',
dataType: 'jsonp',
success: function(response){
console.log(response)
}
});
});
You may be interested in reading What are the differences between JSON and JSONP?
A "JSONP response" from a server is actually an executable script. The client runs the executable script, and the script happens to contain the data you want, supplied as an argument to a function. If the server doesn't serve an executable script, that server does not support JSONP.
For your next error, see "No 'Access-Control-Allow-Origin' header is present on the requested resource". Ajax requests to other domains are not permitted, unless explicitly allowed by CORS headers (like the Access-Control-Allow-Origin response header) from the server. Due to the same-origin policy, scripts on one origin are not allowed to access the contents of another origin. Cross-Origin Resource Sharing (CORS) is a way for the server to relax the same-origin policy.
I would suggest contacting the providers of the API and requesting CORS support. In this case, it really is as simple as serving an Access-Control-Allow-Origin: * header in the response. Per the W3C's own security recommendations for CORS:
A resource that is publicly accessible, with no access control checks, can always safely return an Access-Control-Allow-Origin header whose value is "*".
Alternatively, you can set up a reverse proxy server that fetches the API resources for you and serves them on your own origin, as noted in an answer on Ways to circumvent the same-origin policy. Since the same-origin policy is a browser restriction, you can have any server you control fetch the API resource and then serve the response to your browser.
The default data format is XML, but can be changed by setting the format query variable to "json" to return JSON formatted data.
You need to add &format=json to the end of the URL:
http://opengov.brandon.ca/opendataservice/Default.aspx?date=riverlevel&columns=date&dataset=riverlevel&format=json

I'm getting "Cross-Origin Request Blocked" with the same domain

Well my JavaScript calls the url that is the part of the website, so I have no idea why this is "cross-origin".
My AJAX call:
$.ajax({
url: SITE_URL+'ajax_check.php?p='+P_ID,
//let's say SITE_URL is http://example.com/dev
success:function(result){
alert(result);
}
});
And this is the error I get in firebug:
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com/dev/ajax_check.php?p=23. This can be fixed by moving the resource to the same domain or enabling CORS."
As mentioned by VoteyDisciple the url format must be exactly the same. In my situation the page url had a www prefix, but the ajax call url did not. So that's "cross-origin".

Categories