using jsonp in express.js for node.js

拈花ヽ惹草 提交于 2019-12-10 12:03:17

问题


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:


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) ;
});


来源:https://stackoverflow.com/questions/13928391/using-jsonp-in-express-js-for-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!