0

I am creating a simple JSON API that just returns me an object using jsonp using node-js Here is the code for server side :

app.get('/vit',function  (req,res,next) {
    res.type('application/json');
    res.jsonp(items);  //items is the object
});

On deploying to nodejitsu , and going to url /vit i get the object items.That means its working on the server side.

I have another domain from where I wanna get this object using jsonp Heres the client-side code :

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $.getJSON('http://trial.jit.su/vit',function  (data) {
       console.log(data) ;
    });
</script>

But I get the following error on the console:

XMLHttpRequest cannot load http://trial.jit.su/vit. Origin http://jquer.in is not allowed by Access-Control-Allow-Origin.

Seems like I have not understand Jsonp.

1 Answer 1

6

Quoting the jQuery docs

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

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

You need a query string param with a question mark as placeholder.

And looking at the response of http://trial.jit.su/vit you're missing the callback function. You're just returning plain JSON without the P, e.g. if the url contains ?callback=bacon your response needs to be

bacon({"your": "json string"});

But express will do this for you, as long as you supply a callback param.

So just change the following:

$.getJSON('http://trial.jit.su/vit?callback=?',function  (data) {
    console.log(data) ;
});
Sign up to request clarification or add additional context in comments.

2 Comments

I did a hack ,Its working .Heres the code .. for server side -- app.get('/callback=?*',function (req,res,next) { res.type('application/json'); res.jsonp(items); //items is the object }); ... for the client side $.getJSON('http://trial.jit.su/callback=?',function (data) { console.log(data) ; });
Your server side was just fine. Express will grab the callback param if it's available.

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.