问题描述
我正在创建一个简单的JSON API,它使用node-js使用jsonp返回一个对象这是服务器端的代码:
I am creating a simple JSON API that just returns me an object using jsonp using node-jsHere is the code for server side :
app.get('/vit',function (req,res,next) {
res.type('application/json');
res.jsonp(items); //items is the object
});
在部署到nodejitsu并转到url/vit时,我得到了对象项.这意味着它可以在服务器端工作.
On deploying to nodejitsu , and going to url /vit i get the object items.That means its working on the server side.
我有一个另一个域,我想从这里使用jsonp获取此对象这是客户端代码:
I have another domain from where I wanna get this object using jsonpHeres 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.
好像我不了解Jsonp.
Seems like I have not understand Jsonp.
推荐答案
引用jQuery文档
http://api.jquery.com/jQuery.getJSON/
您需要一个带有问号的占位符的查询字符串参数.
You need a query string param with a question mark as placeholder.
并查看 http://trial.jit.su/vit 的响应,缺少回调函数.您只是返回不带P的纯JSON,例如如果网址包含?callback=bacon
,则您的响应必须为
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"});
但是只要您提供callback
参数,express就会为您完成此操作.
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) ;
});
这篇关于在node.js的express.js中使用jsonp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!