CORS doesn't work - jsonp

i was trying to make asynchronous call to Yahoo's symbol suggest JSONP API, so there's cross domain problem, I have read this document and try to change it's url , the following are the codes i use
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
// var url = 'http://updates.html5rocks.com';
var url = 'http://autoc.finance.yahoo.com/autoc?query=google&callback=YAHOO.Finance.SymbolSuggest.ssCallback';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
console.log(text);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
but the problem still not solved:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
does anyone know why? Also, I compared the code in document with regular ajax code, they are almost the same, how does CORS work?
thanks

For CORS to work, the server needs to set the Access-Control-Allow-Origin header. If you do not control the server, and the server hasn't set that header, then I'm afraid you're out of luck.
CORS replaces JSONP as the way to load cross-domain json content, but with JSONP the server also needs to implement it.
If the owner of the content doesn't want you to use it, the browser will reject it.
Edit: of course you can avoid the cross-browser issue by having your server get the content from the original server, and having the browser get it from your own server. More work, but it's not cross-browser anymore.

Related

No 'Access-Control-Allow-Origin' when using XMLHttpRequest

Following this documentation of Codeship API: https://apidocs.codeship.com/v2/projects/update-project
I am trying to use XMLHttpRequest to fetch the data. The code is generated from the documentation, so I am assuming it should work.
var data = "{}";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://api.codeship.com/v2/organizations/uuidhere/projects?type=basic");
console.log('good');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
console.log('ok');
xhr.setRequestHeader("authorization", token here);
xhr.send(data);
console.log(data)
However, when I test it in my localhost, it gives me
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:3000' is therefore not allowed access. The response had HTTP status code 404.
It's weird that it still happens after putting
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
Please help

How to GET json data from API with a header

I'm trying to get JSON data from an API using NodeJS and Express, but it requires a header I'm not sure how to input the header into the get request.
The documentation says:
curl -H"X-FullContact-APIKey:$your_key"
'https://api.fullcontact.com/v2/person.json?email=bart#fullcontact.com'
How do I do a add a get request with a header? I looked everywhere on Stackoverflow for days, and havent found anything. Everything is for PHP, nothing for NodeJS w/ Express. How can I do this with the Request Node NPM Manager Package
Not sure on how your request code looks like, but this should do it; right?
var request = require('request');
var options = {
url: 'https://api.fullcontact.com/v2/person.json?email=bart#fullcontact.com',
headers: {
'X-FullContact-APIKey': '$your_key'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
console.log(result);
}
}
request(options, callback);

ionic 2: http get request not working (proxy added)

I'm using Http from #angular/http to send GET requests, but the server is not receiving the request. The generated urls are correct because when I log them and open them in browser (I've tried all of Chrome, Firefox and Safari), the server does receive these requests.
This is how I am doing this:
let logButtonUrl = this.urlGenerator.generateTiramisuUrlTemp(this.servletPath,
argMap);
console.log("logButtonUrl:"+logButtonUrl);
return this.http.get(logButtonUrl).map(this.writeSuccess);
Function writeSuccess:
private writeSuccess(res: Response) {
let body = res.json();
let rows_affected = body.data[0].rowsAffected;
if (rows_affected == "1") {
return true;
} else {
return false;
}
}
I got no error message in browser console, so it's probably not because of the CORS issue discussed here:
http://blog.ionic.io/handling-cors-issues-in-ionic/
I also tried using a proxy. I added this in ionic.config.json:
{
"path": "/backendTemp",
proxyUrl": "http://128.237.217.70:8080" /*the ip address of the target server*/
}
And replace the ip address in my generated urls with "/backendTemp". Still not working.
Any suggestions/thoughts on this? Thanks a lot!
Use the $http (https://docs.angularjs.org/api/ng/service/$http):
.controller('RequestCtrl', function ($http) {
$http({
method: 'GET',
url: 'http://128.237.217.70:8080/backendTemp'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

xmlhttprequest in chrome extension

I am developing a chrome extension and I have an iframe which I use in my extension. This is what I do with my iframe
"When I drag and drop a image to my iframe I handle the drop event in one of the content scripts and pass that function call my extension code. There I create a xmlhttprequest object and then send the URL of the image to a php file in my server."
This is what is happening. I get a readyState of "4" but there is no POST request going out of my browser. I checked with the "NETWORK" tab in the browser but there is no POST request going out of the browser (I have listed my site in the permissions section of the manifest file).
This is my code --.>
JScript.js(One of the content scripts )
drop: function(event, ui) {
var imgurl=$(ui.draggable).attr('src');
imgurl="IMGURL="+imgurl;
_post("www.somedomain.come/testing.php",imgurl,function(result){ alert("success")});
}
This is my proxy in the same content script-->
_post = function(url, data, callback)
{
console.log("sending post");
chrome.extension.sendRequest({
msgType:'post',
data: data,
url:url
}, function(response){
alert(response);
});
}
This my OnRequest function handler in background.html -->
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
if (request.msgType === 'post') {
alert("Now in OnRequest function");
// console.log("Now in Onrequest Function");
alert("Url: "+request.url + "\n Data : "+ request.data);
ajaxcallingfunction(request);
alert("completed the ajax call");
sendResponse("success");
}
});
var ajaxcallingfunction = function(request){
var xhr = new XMLHttpRequest();
xhr.open("POST",request.url, false);
xhr.onreadystatechange = function(){
alert(xhr.readyState);
if (xhr.readyState == 4) {
alert(xhr.readyState);
}
}
xhr.send(request.data);
alert("after xhr call");
};
You have http:// in front of your url, right?
xhr.readyState doesn't tell much, it just means that it is done. Check out what's inside xhr.status, it would contain error code. If everything is ok it should be 200:
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
alert(xhr.status);
}
}

How do I write a Node.js request to 3rd party API?

Does anyone have an example of an API response being passed back from a http.request() made to a 3rd party back to my clientSever and written out to a clients browser?
I keep getting stuck in what I'm sure is simple logic. I'm using express from reading the docs it doesn't seem to supply an abstraction for this.
Thanks
Note that the answer here is a little out of date-- You'll get a deprecated warning. The 2013 equivalent might be:
app.get('/log/goal', function(req, res){
var options = {
host : 'www.example.com',
path : '/api/action/param1/value1/param2/value2',
port : 80,
method : 'GET'
}
var request = http.request(options, function(response){
var body = ""
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
res.send(JSON.parse(body));
});
});
request.on('error', function(e) {
console.log('Problem with request: ' + e.message);
});
request.end();
});
I would also recommend the request module if you're going to be writing a lot of these. It'll save you a lot of keystrokes in the long run!
Here is a quick example of accessing an external API in an express get function:
app.get('/log/goal', function(req, res){
//Setup your client
var client = http.createClient(80, 'http://[put the base url to the api here]');
//Setup the request by passing the parameters in the URL (REST API)
var request = client.request('GET', '/api/action/param1/value1/param2/value2', {"host":"[put base url here again]"});
request.addListener("response", function(response) { //Add listener to watch for the response
var body = "";
response.addListener("data", function(data) { //Add listener for the actual data
body += data; //Append all data coming from api to the body variable
});
response.addListener("end", function() { //When the response ends, do what you will with the data
var response = JSON.parse(body); //In this example, I am parsing a JSON response
});
});
request.end();
res.send(response); //Print the response to the screen
});
Hope that helps!
This example looks pretty similar to what you are trying to achieve (pure Node.js, no express):
http://blog.tredix.com/2011/03/partly-cloudy-nodejs-and-ifs.html
HTH