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?

1

4 Answers 4

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)});
Sign up to request clarification or add additional context in comments.

Comments

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/

Comments

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 *************/

1 Comment

He's trying to make a JSONP API, so this is not necessary.
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);
}); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.