在express.js中使用jsonp作为node.js

jay*_*iya 0 jsonp node.js express

我正在创建一个简单的JSON API,它只使用jsonp使用node-js返回一个对象.这是服务器端的代码:

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

在部署到nodejitsu,并转到url/vit时,我得到了对象项.这意味着它在服务器端工作.

我有另一个域,我想在哪里使用jsonp获取此对象Heres客户端代码:

<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>
Run Code Online (Sandbox Code Playgroud)

但是我在控制台上收到以下错误:

XMLHttpRequest cannot load http://trial.jit.su/vit. Origin http://jquer.in is not allowed by Access-Control-Allow-Origin.
Run Code Online (Sandbox Code Playgroud)

好像我还不懂Jsonp.

Pri*_*orn 6

引用jQuery文档

如果URL包含字符串"callback =?" (或类似的,由服务器端API定义),请求被视为JSONP.有关更多详细信息,请参阅$ .ajax()中有关jsonp数据类型的讨论.

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

您需要一个带有问号作为占位符的查询字符串参数.

看看http://trial.jit.su/vit的响应你就错过了回调函数.你只是在没有P的情况下返回普通的JSON,例如,如果url包含?callback=bacon你的响应需要

bacon({"your": "json string"});
Run Code Online (Sandbox Code Playgroud)

但是快递会为你做这件事,只要你提供一个callback参数.

所以只需更改以下内容:

$.getJSON('http://trial.jit.su/vit?callback=?',function  (data) {
    console.log(data) ;
});
Run Code Online (Sandbox Code Playgroud)