0

I'm pretty sure JSONP means no cross domain restrictions. I'm trying to make a JSONP service using node and express. Here is simple code:

self.routes['/portfolio'] = function(req, res) {
      // Website you wish to allow to connect
         res.jsonp({ "my": "object" });
};

When I do:

$.getJSON('http://127.0.0.1:8080/portfolio', function(data){ console.log(data)});

I get this error.

XMLHttpRequest cannot load http://127.0.0.1:8080/portfolio. The 'Access-Control-Allow-Origin' header has a value 'http://127.0.0.1:8080/portfolio' that is not equal to the supplied origin. Origin 'http://api.jquery.com' is therefore not allowed access.

Can someone explain what is going on here? Why do we need to supply header value if this is JSONP. How can I make this work cross domain?

JS-JMS-WEB
  • 2,555
  • 3
  • 17
  • 26
  • check this http://stackoverflow.com/questions/11916780/changing-getjson-to-jsonp You need to add callback call also – Abhijith A C Aug 12 '15 at 13:43

4 Answers4

3

$.getJSON does not treat the request as JSONP unless the request URL includes a string like callback=?.

So, try doing this instead;

$.getJSON('http://127.0.0.1:8080/portfolio?callback=?', function(data){ console.log(data)});
Dal Hundal
  • 3,234
  • 16
  • 21
1

Actually, you just have to add ?callback=?, jQuery does the rest.

  $(document).ready(function() {
        $.getJSON('http://127.0.0.1:8080/portfolio?callback=?', function(data) {
            console.log(data);
        });
    });

Source: http://api.jquery.com/jQuery.getJSON/

Juned Lanja
  • 1,466
  • 10
  • 21
0

Put below code into app.js or server.js

/*************To Allow access to cross domain request *************/

   app.all('*', function(req, res, next) {
           res.header('Access-Control-Allow-Origin', '*');
           res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
           res.header('Access-Control-Allow-Headers', 'Content-Type');
           next();
   });

   /*************To Allow access to cross domain request *************/
Love-Kesh
  • 777
  • 7
  • 17
0

Use $.ajax with dataType jsonp

$.ajax({
    type: 'GET',
    cache: false,
    url: 'http://portfoliomanager-sran.rhcloud.com/portfolio?callback=?',
    dataType: 'jsonp'  
}).then(function(response){
console.log(response);
}); 
Abhijith A C
  • 530
  • 2
  • 7
  • 21