Tumblr API OAuth with local test server - javascript

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.

Related

How to remove automatically added connections proxy in XCC?

I want to make an ajax request from IBM Connections XCC:
let api = 'https://my-server2/api.xml'
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = () => {
if (xmlhttp.readyState == XMLHttpRequest.DONE)
if (xmlhttp.status == 200) {
console.log(xmlhttp.responseText)
}else {
console.log(`Error: ${xmlhttp.readyState}`)
}
}
Result in the network tab is a request to https://connections-host/communities/ajaxProxy/https/my-server2/api.xml so the request is proxied over the connections server. Because of this I get an empty API result since I need an authorized user session. My idea was: The user is logged in in his browser on my-server2 application. So when making an ajax request to my-server2, I can get the API information in his user context.
So my question is: How can I bypass those proxy?
Since I don't set it, I assume that connections manipulate the XMLHttpRequest class in a way like this: https://gist.github.com/dewdad/8830348
I want to view it's code to see the manipulation with this code in the console, but it only shows native code
window.XMLHttpRequest.prototype.open.toString()
"function open() {
[native code]
}"
Connections uses an AJAX proxy to control what's sent out to non-Connections sites/apps. You can configure it for your site to allow specific methods, headers and cookies to be sent to the non-Connections site. I'd take a look at this document on Connections 6.0 https://www.ibm.com/support/knowledgecenter/en/SSYGQH_6.0.0/admin/secure/t_admin_config_ajax_proxy_feature.html
I think that should help you get what you want.

MailChimp API 3.0 xhr subscribe 501 error

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.

CORS error when accessing local JSON file using vanilla JS AJAX request?

I am trying to use a vanilla JS AJAX request to pull back a JSON string from a locally stored JSON file (specifically trying not to use JQuery) - the below code is based on this answer - but I keep getting an error in the Chrome console (see below). Any ideas where I'm going wrong? I have tried changing the positioning of the xhr.open & .send requests, but still get error messages. I suspect the issue lies with the .send() request?
//Vanilla JS AJAX request to get species from JSON file & populate Select box
function getJSON(path,callback) {
var xhr = new XMLHttpRequest(); //Instantiate new request
xhr.open('GET', path ,true); //prepare asynch GET request
xhr.send(); //send request
xhr.onreadystatechange = function(){ //everytime ready state changes (0-4), check it
if (xhr.readyState === 4) { //if request finished & response ready (4)
if (xhr.status === 0 || xhr.status === 200) { //then if status OK (local file || server)
var data = JSON.parse(xhr.responseText); //parse the returned JSON string
if (callback) {callback(data);} //if specified, run callback on data returned
}
}
};
}
//-----------------------------------------------------------------------------
//Test execute above function with callback
getJSON('js/species.json', function(data){
console.log(data);
});
The console in Chrome is throwing this error:
"XMLHttpRequest cannot load file:///C:/Users/brett/Desktop/SightingsDB/js/species.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."
Would be grateful for any insights - many thanks.
Basically as Felix, error msg, et al below say - simply can't run an AJAX request against a local file.
Thanks.
Try to run the application on local server like apache or wamp then you will not face any issue

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I'm attempting to send a XMLHttpRequest to a paste site. I'm sending an object containing all the fields that the api requires, but I keep getting this issue. I have read over the issue, and I thought:
httpReq.setRequestHeader('Access-Control-Allow-Headers', '*');
Would fix it,but it didn't. Does anyone have any information on this error and/or how I can fix it?
Here is my code:
(function () {
'use strict';
var httpReq = new XMLHttpRequest();
var url = 'http://paste.ee/api';
var fields = 'key=public&description=test&paste=this is a test paste&format=JSON';
var fields2 = {key: 'public', description: 'test', paste: 'this is a test paste', format: 'JSON'};
httpReq.open('POST', url, true);
console.log('good');
httpReq.setRequestHeader('Access-Control-Allow-Headers', '*');
httpReq.setRequestHeader('Content-type', 'application/ecmascript');
httpReq.setRequestHeader('Access-Control-Allow-Origin', '*');
console.log('ok');
httpReq.onreadystatechange = function () {
console.log('test');
if (httpReq.readyState === 4 && httpReq.status === 'success') {
console.log('test');
alert(httpReq.responseText);
}
};
httpReq.send(fields2);
}());
And here is the exact console output:
good
ok
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:40217' is therefore not allowed access. http://paste.ee/api
XMLHttpRequest cannot load http://paste.ee/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:40217' is therefore not allowed access. index.html:1
test
Here is the console output when I test it locally on a regular Chromium browser:
good
ok
XMLHttpRequest cannot load http://paste.ee/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. index.html:1
test
I think you've missed the point of access control.
A quick recap on why CORS exists:
Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.
Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.
In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).
I've gotten same problem.
The servers logs showed:
DEBUG: <-- origin: null
I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine
function cors() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("emo").innerHTML = alert(this.responseText);
}
};
xhttp.withCredentials = true;
xhttp.open("GET", "http://owasp-class.lab:4444/api/get_info", true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencode');
xhttp.send();
}

Track 404 error pages or How to monitor http header request's status made by the browser using Javascript

I am developing a script that helps track 404 error pages (using JavaScript) at the client side. I searched for tutorials/ posts on the same but didn't find any helpful to me.
One post mentioned using curl (PHP) on the server side & redirect the user to a custom 404 page. But that doesn't address my problem (I want it at the client side).
This page mentions how to create an http object, open up a connection & detect its status in this way:
var request = makeHttpObject();
request.open("GET", "your_url", true);
request.send(null);
....
if( request.status == 404 )
print("404 error")
But over here we ourselves are making the http request & hence have access to the object. My aim is to detect any 404 page errors from the request send by the browser (due to user navigation).
Can we monitor the browser's http object for response statuses? How does Firebug's Network Analysis feature access the http headers? Can I replicate that in my script?
I have noticed that browser's Developer tool's Console gives a 404 error for missing pages as well as individual elements like images on that page.
These are the possible solutions I could imagine:
Monitor the response.status of every http request sent by the browser
Use Developer Tool's/Browser's Error Notification to track 404 errors using an "API" for extracting those error notifications of the tool (if it exists)
Thanks a lot
You mean something like this?
function returnStatus(req, status) {
//console.log(req);
if(status == 404) {
console.log("The url returned status code " + status);
}
else {
console.log("success");
}
}
function fetchStatus(address) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == 4)
returnStatus(this, this.status);
}
client.open("HEAD", address);
client.send();
}
fetchStatus("http://yoururl.com");

Categories

Resources