How to set up CORS in an AJAX request - javascript

I have been working on a personal webapp and have hit a little snag. My API calls only work for some APIs and not for others. For the ones it doesn't work with I will usually get an error message like so.
XMLHttpRequest cannot load https://api.meetup.com/2/cities. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
After doing some research I know it is to do with CORS not being setup. I was wondering if it would be possible to set this up in the client when making an AJAX request. The current way I am doing this is like so
var handleRequest = function(request){
$.ajax({
type: "GET",
url: request,
success: function(data) {
var rawJSON = JSON.stringify(data, null, 2);
editor.setValue(rawJSON);
},
dataType: 'json'
});

The server you're trying to access has to grant you permission to access it. An IT admin has to provide you with a URL that grants you permission to hit their external server. The server you are trying to hit has to setup CORS. http://enable-cors.org/

According to their docs they support JSONP.
https://www.meetup.com/meetup_api/
This is your way around CORS.

Related

No 'Access-Control-Allow-Origin' header is present on the requested resource in simple html form

why this error is showing in my simple html form, I want to get xml data in my simple form to show news on my webpage, but this error is showing continuously, please help
$.ajax({
type: "GET",
url: "https://news.google.com/rss/search?q=Nigeria&hl=en-PK&gl=PK&ceid=PK:en",
dataType: "xml",
success: function(xml) {
console.log(xml)
}
});
It is up to the server that has the resource to allow cross origin access.
Probably there is API for what you are trying to do. API gets implemented by the resource owner and provides controlled access.
Or you can use RSS if there is one.
What you could potentially do is run your requests through a CORS proxy. For example:
$.ajax({
type: "GET",
url: "https://cors-anywhere.herokuapp.com/https://news.google.com/rss/search?q=Nigeria&hl=en-PK&gl=PK&ceid=PK:en",
dataType: "xml",
success: function(xml) {
console.log(xml)
}
});
You can see that this works by simply pasting this code snippet into the console.
This essentially bypasses the CORS issues for you. I would only recommend using this hosted version if you don't have a lot of traffic, otherwise you should host your own version of the CORS proxy.
This is because of CORS(Cross Origin Resource Sharing) policy implemented by browsers. Which means browsers doesn't allow certain requests to be sent from a domain to another domain. However this is not applicable to all type of requests.
Check this link to understand what all requests come under this policy
Inorder to make this work , the other server, in your case https://news.google.com, have to setup in such a way that it allows cross domain requests. This is achieved by servers telling the browser that it is ready to accept cross domain requests from your domain, by adding certain cors related headers. One such is Access-Control-Allow-Origin. But I am afraid you can't do it since you aren't the one managing this server.
Work-Around
Use your backend to send the request to google. So that your xhr request calls your server and your server calls google. No browser No Cors.
xhr---> yourdomain.com/news/get---> someotherdomain.com/news/get

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".

Creating wallet on Blockchain with Ajax gives CORS error

I am trying to create wallet on Blockchain using Ajax but I am getting "Cross-Origin Request Blocked" error. My Ajax call is:
$.ajax({
type: 'POST',
url: 'https://blockchain.info/api/v2/create_wallet',
data: "cors=true&email="+email+"&password="+password+"&api_code="+code,
dataType:'json',
crossDomain: true,
beforeSend:function(){
},
success: function (data) {
}
});
When I post this I get error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://blockchain.info/api/v2/create_wallet. This can be fixed by moving the resource to the same domain or enabling CORS.
On Blockchain they say that Some API calls are available with CORS headers if you add a cors=true parameter to the request
I have tried everything, I have tried to send this parameter as a GET as well as POST parameter, I have tried jsonp. I have also tried with the header Access-Control-Allow-Origin * but nothing seems to be working. Can anyone confirm if he managed to create blockchain wallet using Ajax call or they don't support CORS for this. Any help will be much appreciated.
Thanks
Hamza
I think it is safe to say that blockchain does not support CORS for their wallet API.
Your AJAX call above looks correct and you are getting a CORS blocked error.
And unlike some of their other APIs, the blockchain wallet API docs at https://blockchain.info/api/blockchain_wallet_api do not specify that calls are available via CORS with the cors=true query parameter.
There are some significant security implications when dealing with private keys and passwords in the browser using javascript. I suspect that is why they do not allow it.
The solution for this is insanely simple. Just do that request on the server side and then call your server script which does that request from your $.ajax() method.

I thought ajax was same orgin policy?

I'm confused about the same domain orgin policy with jquery ajax. If i make a get request to a url with jquery, I can get the results back. What am I missing? I thought it was restricted to same orgin policy.
$(function () {
var data;
var x = $.ajax({
dataType: 'json',
url: 'http://jsonplaceholder.typicode.com/posts',
data: data,
success: function(){ console.log("true");},
failure: function(){console.log("failed");}
});
console.log(x);
});
See this page.
API can be accessed from your development environment through CORS or JSONP.
Yes, it is, but the website you are requesting specifically allows CORS (cross-origin resource sharing) as well as JSONP requests, meaning you can request the data from another origin using either one of those methods. Using the .ajax() method with dataType: 'json' means you are using CORS. You could also make a JSONP request with dataType: 'jsonp'.
Both CORS and JSONP are specific server options that can be enabled to allow users to request data from another origin. Keep in mind that the data could be modified on the server to be malicious, so it could be a potential security hole if you begin using that data. Be sure to only use CORS or JSONP with a service you trust.

Categories