与JSONP AngularJS资源服务失败 [英] AngularJS resource service with jsonp fails

查看:86
本文介绍了与JSONP AngularJS资源服务失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要获取在AngularJS一个REST API的JSON输出。下面是我所面临的问题:

I'm trying to fetch the JSON output of a rest api in AngularJS. Here are the problems I'm facing:


  • 的REST API网址具有正由AngularJS用于可变插在它的端口号。我想这几项决议是徒劳的。

  • 我在使用JSONP方法的问题。 REST API是不是托管在同一域/服务器上,因此一个简单的GET不工作。

  • 来的REST API的参数是斜线分开,而不是像一个HTML查询字符串。其中一个参数是一个电子邮件地址,我想在'@'符号会引起一些问题,以及。我没能要么解决这个问题。

我的REST API看起来类似: http://myserver.com:8888/dosomething/me@mydomain.com/arg2
示例code /文件将是非常有益的。

My rest api looks something like: http://myserver.com:8888/dosomething/me@mydomain.com/arg2. Sample code / documentation would be really helpful.

推荐答案

我挣扎了很多这样的问题,所以希望这将帮助别人的未来:)

I struggled a lot with this problem, so hopefully this will help someone in the future :)

JSONP需要一个回调函数,一个常见的​​错误是调用返回JSON的URL,你会得到的未捕获的SyntaxError:意外的标记:的错误。相反,JSONP应该返回这样的事情(不要在本例中得到挂在函数名):

JSONP expects a function callback, a common mistake is to call a URL that returns JSON and you get a Uncaught SyntaxError: Unexpected token : error. Instead, JSONP should return something like this (don't get hung up on the function name in the example):

angular.callbacks._0({"id":4,"name":"Joe"})

借助文档告诉你传递JSON_CALLBACK的URL的一个原因。这将被替换为回调函数的名称来处理的回报。每个JSONP请求被分配一个回调函数,所以如果你做多的请求,他们可能会通过angular.callbacks._1,angular.callbacks._2处理等等。

The documentation tells you to pass JSON_CALLBACK on the URL for a reason. That will get replaced with the callback function name to handle the return. Each JSONP request is assigned a callback function, so if you do multiple requests they may be handled by angular.callbacks._1, angular.callbacks._2 and so forth.

考虑到这一点,你的要求应该是这样的:

With that in mind, your request should be something like this:

var url = 'http://myserver.com:8888/dosomething/me@mydomain.com/arg2';
$http.jsonp(url + '?callback=JSON_CALLBACK')
   .then(function (response) {
       $scope.mydata = response.data;
       ...

然后AngularJS实际上将请求(更换JSON_CALLBACK):

Then AngularJS will actually request (replacing JSON_CALLBACK):

http://myserver.com:8888/dosomething/me@mydomain.com/arg2?callback=angular.callbacks._0

一些框架有JSONP支持,但如果您的API不会自动做,你可以从查询字符串获取回调名封装JSON。
例子是在Node.js的:

Some frameworks have support for JSONP, but if your api doesn't do it automatically, you can get the callback name from the querystring to encapsulate the json. Example is in Node.js:

var request = require('request');
var express = require('express');
var app = express();

app.get('/', function(req, res){
    // do something to get the json
    var json = '{"id":4,"name":"Joe"}';

    res.writeHead(200, {"Content-Type": "application/javascript"});
    res.write(req.query.callback + '(' + json + ')');
    res.end();
});
app.listen(8888);

这篇关于与JSONP AngularJS资源服务失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆