MailChimp API 3.0 xhr subscribe 501 error - javascript

I am trying to subscribe users to my mailchimp list using this snippet:
function subscribeUser(name, email) {
var xhr = new XMLHttpRequest();
var endpoint = 'https://<dc>.api.mailchimp.com/3.0/lists/<list>/members/';
var data = {};
data.email_address = email;
data.status = "subscribed";
data.merge_fields = {};
data.merge_fields.NAME = name;
xhr.open("POST", endpoint, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "apikey <key>");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(data);
}
It generates this error in chrome:
I am unable to write ajax based services to update lists. Because you guys did not add the Access Control header. I cannot send a simple xhr to your endpoint using a modern browser.
XMLHttpRequest cannot load https://<dc>.api.mailchimp.com/3.0/lists/<list>/members/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 501.
Mine is a static website and I would like to keep it that way. No backend is needed, hosted on github. So I need a JS solution to this.

They currently do not allow client-side access to their API. Their response to a similar question in comments:
We do not support accessing the API via client-side Javascript to
avoid the security issue of passing your API Key along to your users.

Related

Ebay Trading API Get Item Ajax Request

I want to made simple post request on Ebay trading api with javascript Ajax. Here is the call format. I got some error on the following request. can anyone tell me the what wrong with the call .
const findbtn = document.querySelector(".find-item-btn");
findbtn.addEventListener("click", getData);
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log(this.responseText);
};
const xml =
'<?xml version="1.0" encoding="utf-8"?>' +
'<GetItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">' +
"<ErrorLanguage>en_US</ErrorLanguage>" +
"<WarningLevel>High</WarningLevel>" +
"<ItemID>232789363104</ItemID>" +
"</GetItemRequest>";
xhttp.open("POST", "https://api.ebay.com/ws/api.dll", true);
xhttp.setRequestHeader("X-EBAY-API-COMPATIBILITY-LEVEL", "967");
xhttp.setRequestHeader("X-EBAY-API-DEV-NAME","6cfe5ebb-73c4-465b-ad24-c4f0aea8de0");
xhttp.setRequestHeader("X-EBAY-API-APP-NAME","RegnantC-SaveWix-PRD-3ef66784f-24730a7");
xhttp.setRequestHeader("X-EBAY-API-CERT-NAME","PRD-ef66784f85c1-6c65-4919-bc83-24c6");
xhttp.setRequestHeader("X-EBAY-API-CALL-NAME", "GetItem");
xhttp.setRequestHeader("X-EBAY-API-SITEID", "0");
xhttp.setRequestHeader("Content-Type", "text/xml");
xhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xhttp.setRequestHeader("Access-Control-Allow-Headers","X-Requested-With, Origin, Content-Type, X-Auth-Token");
xhttp.setRequestHeader("Access-Control-Allow-Methods","GET, PUT, POST, DELETE");
xhttp.setRequestHeader("X-EBAY-API-IAF-TOKEN","v^1.1#i^1#f^0#r^0#p^3#I^3#t^H4sIAAAAAAAAAOVYeWwUVRjv9lJEaIigTUWzTiEeOLtz7e7sh"
);
xhttp.send(xml);
}
and got the following error
1 Access to XMLHttpRequest at 'https://api.ebay.com/ws/api.dll' from origin 'localhost/app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
2 POST https://api.ebay.com/ws/api.dll net::ERR_FAILED
Please help me. is the right format for the ajax request
Actually it's causing the CORS error. You can read about it details from here https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
And if you want to overcome this issue you can enable CORS from server. I mean send the request through your server.
Or you can also use CORS anywhere header.
const corsHeader = "https://cors-anywhere.herokuapp.com/";
then use this corsHeader appending with your url like this,
xhttp.open("POST", corsHeader+"https://api.ebay.com/ws/api.dll", true);
It'll send the request and currently it's showing error: IAF token supplied is invalid. If you provide proper IAF token then it'll provide you the data.
I'm very new to programming in general so this will not be a technical answer in the least, but.... I did get this to eliminate the CORS error.
const corsHeader = "https://cors-anywhere.herokuapp.com/";
xhttp.open("POST", "https://api.ebay.com/identity/v1/oauth2/token", true);
xhttp.open("POST", corsHeader, true);
I had to go here first and enable temporary access though.
https://cors-anywhere.herokuapp.com/corsdemo
Now when I run this the console is saying:
"This API enables cross-origin requests to anywhere."
If I can figure out how to get any farther I will update this thread.

OAuth Authentication - Access Token using JavaScript (CORS Policy) error

I'm embedding Power BI Reports into another application using JavaScript and I could generate access token (Barear) using below JavaScript code but it doesn't work in all the browsers. It displays below error message.
Access to XMLHttpRequest at 'https://login.microsoftonline.com/<>/oauth2/token' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I added required request headers but still the same result.
var key;
var request = new XMLHttpRequest();
request.open("POST", "https://login.microsoftonline.com/<<tenant_id>>/oauth2/token", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader('Access-Control-Allow-Headers', 'x-requested-with');
request.setRequestHeader('Access-Control-Allow-Origin', '*');
request.send("grant_type=client_credentials&client_id=<<clientid>>&client_secret=<<clientsecret>>&resource:<<resourceurl>>"); // specify the credentials to receive the token on request
request.onreadystatechange = function () {
if (request.readyState == request.DONE) {
var response = request.responseText;
var obj = JSON.parse(response);
key = obj.access_token;
token_ = key;
}
}
Any ideas?
Thank you!
You should never put the client secret in the front-end.
We suggest you use azure-activedirectory-library-for-js for frontend to integrate AAD with a ease. You can refer to No 'Access-Control-Allow-Origin' header with Microsoft Online Auth for details.
client_credentials grant_type is used in app only scenario. If you must use client credential flow, you need to get the access token in your app's backend and return it to the frontend.

Response to preflight request doesn't pass access control check error

The exact error that I am struggling with is "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 am trying to fetch JSON data using JavaScript from https://api.kraken.com/0/public/OHLC?pair=ETHEUR. I created a XMLHttpRequest object to do this, and specified GET as the type of request. This is supposedly a simple request, however the error says that a preflight request was sent. What is the reason for this behavior? That being said, to fix this error I tried to set a request header in which I specified '*' as the value for the Access-Control-Allow-Origin, yet I still get an error. I have looked through responses to similar questions as mine, but haven't been able to figure out how to solve the problem I am dealing with. This is probably due to still being very new to JavaScript. Either way, below is the code that I have written:
var requestURL = 'https://api.kraken.com/0/public/OHLC?pair=ETHEUR'
var request = new XMLHttpRequest();
request.open('GET',requestURL,true);
request.responseType = 'json';
request.onload = function(){
var data = request.response;
console.log(data);
}
request.setRequestHeader('Access-Control-Allow-Origin','*');
request.send();
In cases like this where the server you’re trying to make a cross-origin request to doesn’t send the Access-Control-Allow-Origin response header, your only option, if you want to make a request to that server from frontend JavaScript code running in a browser, is to use a CORS proxy. Otherwise, your browser won’t allow your frontend JavaScript code to access the response.
So, you can make your request succeed if you change your code to have something like this:
var proxyURL = 'https://cors-anywhere.herokuapp.com';
var requestURL = 'https://api.kraken.com/0/public/OHLC?pair=ETHEUR';
var request = new XMLHttpRequest();
request.open('GET', proxyURL + '/' + requestURL, true);
That sends the request through https://cors-anywhere.herokuapp.com, which forwards the request to https://api.kraken.com/0/public/OHLC?pair=ETHEUR and then receives the response. The https://cors-anywhere.herokuapp.com backend adds the Access-Control-Allow-Origin header to the response and passes that back to your requesting frontend code.
The browser will then allow your frontend code to access the response because that response with the Access-Control-Allow-Origin response header is what the browser sees.
You can also easily set up your own CORS proxy using https://github.com/Rob--W/cors-anywhere/
Note also that request.setRequestHeader('Access-Control-Allow-Origin','*') needs to be removed from the frontend code you are making the request with (as mentioned in comments above).
That’s because Access-Control-Allow-Origin is strictly a response header for servers to send in responses; sending it from the client side in a request will have no effect other than to trigger your browser to do an unnecessary CORS preflight OPTIONS request that will fail.
For details about what browsers do when you send cross-origin requests from frontend JavaScript code using XHR or the Fetch API or AJAX methods from JavaScript libraries—and details about what response headers must be received in order for browsers to allow frontend code to access the responses—see https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.
var proxyURL = 'https://cors-anywhere.herokuapp.com';
var requestURL = 'https://api.kraken.com/0/public/OHLC?pair=ETHEUR';
var request = new XMLHttpRequest();
request.open('GET', proxyURL + '/' + requestURL, true);
request.responseType = 'json';
request.onload = function() {
var data = request.response;
document.querySelector('pre').textContent = JSON.stringify(data, null, 2);
}
request.send();
<pre></pre>

Tumblr API OAuth with local test server

I'm trying to get posts from my tumblr blog and put them on a separate website page. To do this I registered an app on their OAuth page, but I'm having some issues when I try to actually request the authorization. My console spits out this message—
XMLHttpRequest cannot load https://api.tumblr.com/v2/blog/myblog.tumblr.com/posts?api_key=(MY_KEY).
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://127.0.0.1:63342' is therefore not allowed access.
(I've omitted the key value here for obvious reasons).
Now, my site isn't actually live yet, and I have a test server running at localhost:63342 but on their OAuth app settings page I have these options that I must fill out—
Is there a way to get this to work with my local test server? Here's the code that I'm calling to request access.
var request = new XMLHttpRequest();
request.open('GET', 'https://api.tumblr.com/v2/blog/myblog.tumblr.com/posts?api_key=(API_KEY)', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
console.log(data);
} else {
// We reached our target server, but it returned an error
console.log('server error');
}
};
request.onerror = function() {
// There was a connection error of some sort
console.log("ERROR!!!");
};
request.send();
Any help would be appreciated! Thanks!
Turn out my issue was using JSON instead of JSONP, which bypasses the Access-Control-Allow-Origin issue. I downloaded this JSONP library for Javascript ( I am not using JQuery in my project ) and was able to access the api by writing this:
JSONP('https://api.tumblr.com/v2/blog/myblog.tumblr.com/posts?api_key=(API_KEY)'
, function(data) {
console.log(data);
});
Which returns a JSON Object which I can then data from using something like data.response or whatever objects are in the array.
Again, my issue was not Tumblr not authorizing my test server. I was able to get this to work using 127.0.0.1:port as my application website & callback url.

Chrome Extension blocked from a rails API

I am just trying to talk with a REST api on a Rails site.
I am using a Chrome extension and javascript to make a CORSRequest.
I get this error whenever I try to make a request:
XMLHttpRequest cannot load https://MYWEBSITE.com/api/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://mychomreextensioncode' is therefore not allowed access. The response had HTTP status code 404.
Here is my current code:
function makeCorsRequestLogin() {
var url = "https://MYWEBSITE.com/api/login";
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onload = function() {
var text = xhr.responseText;
var title = text; //getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
if (!xhr) {
alert('CORS not supported');
return;
}
xhr.onerror = function() {
alert('Woops, there\'s an error making the request.');
};
var password = document.getElementById("password").value;
var user_name = document.getElementById("username").value;
xhr.send(JSON.stringify({"user_name":user_name, "password":password}));
}
Elsewhere, in the past, people have said that this code solves it. But, I have no idea where this could would go.
# This is used to allow the cross origin POST requests made by confroom kiosk app.
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = "*"
headers['Access-Control-Request-Method'] = %w{GET POST OPTIONS}.join(",")
end
I am only working in JS and HTML on a chrome extension. I do not have access to the ruby site. Can I solve this problem from only my end?
You should define permission for your server domain in the manifest.json.
"permissions": ["https://MYWEBSITE.com/*"]
Also make sure you set the right protocol whether it's http or https.

Categories

Resources