AngularJS中带有$ http的HTTP JSONP请求问题 [英] HTTP JSONP request issue with $http in AngularJS
问题描述
当我尝试在angularJS中使用 JSONP
方法时,我收到了波纹管错误。
Uncaught SyntaxError:意外的令牌:
知道我做错了什么吗?或者它是如何配置API服务的问题?
解决方案这里你去: - )
您尝试使用
jsonp
请求的代码看起来不错,但您使用的网址不支持jsonp
请求,这就是您收到错误的原因。
如果您使用
$ http.get $尝试相同的网址c $ c>,它会正常工作。
要支持
jsonp
调用,响应应该包含在JSON_CALLBACK()
如下所示JSON_CALLBACK({/ * JSON * /})
因此,我将此更改为有效
jsonp
url并且它有效!
https://angularjs.org/greet.php?callback=JSON_CALLBACK
您可以在浏览器中尝试此网址并查看响应,如何用
JSON_CALLBACK()$ c包装$ c>。
但如果你尝试下面的网址,你可以看到
json
而不进行任何包装。
http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json?callback=JSON_CALLBACK
这是区别,以查找是否api支持
jsonp
。
另外,我更改了
服务
下面的语法与另一个SO
问题答案相同,
https://stackoverflow.com/a/41030976/7055233
工作代码段:
var app = angular.module('app', []); app.controller('mainController',['$ http','mainService',函数($ http,mainService){mainCtrl = this; mainCtrl.test =如果你能看到这个mainController工作var promise = mainService.getJson (); promise.then(function(data){mainCtrl.json = data;});}]); app.service(mainService,function($ http,$ q){var deferred = $ q.defer( ); var url ='https://angularjs.org/greet.php'; // var url ='http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json'; / * //获取已启用COR的JSON的方法://启用了CORs的JSON资源var url ='https://jsonplaceholder.typicode.com/posts/1'; $ http({method:'GET',cache:true,url :url,headers:{'Content-Type':'application / json; charset = UTF-8'}})。success(function(response){//成功延迟时的代码.resolve(响应); console.log ('HTTP CORS SUCCESS!');})。error(function(response){//失败时的代码console.log('HTTP CORS ERROR!');}); * / / * * / //获取已启用COR的JSON的方法://没有启用CORs的JSON资源函数getJson(){// $ http.jsonp (url +?callback = JSON_CALLBACK)。 //这不起作用$ http.jsonp(url +'?callback = JSON_CALLBACK')。然后(函数(响应){//你的代码成功deferred.resolve(响应); console.log('JSONP SUCCESS!');},函数(响应){//你的代码失败时console.log('JSONP ERROR!'); deferred.reject(response);}); return deferred.promise; } this.getJson = getJson;});
< !DOCTYPE html>< html lang =enng-app =app>< head> < meta charset =UTF-8> <标题>文件< /标题> < script src =http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js>< / script> < script src =http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular-route.js>< / script> <! - < script src =app.js>< / script> - >< / head>< body ng-controller =mainController as mainCtrl> < p为H. {{mainCtrl.test}}< / p为H. < hr /> < p>您还应该看到下面的JSON对象:< / p> {{mainCtrl.json}}< / body>< / html>
I get the bellow error when I try to use the
JSONP
method in angularJS.Uncaught SyntaxError: Unexpected token : http://example.com/getSomeJson?format=jsonp&json_callback=angular.callbacks._0
What am I doing wrong here, this is my AngularJs controller with the http request:
UPDATED QUESTION DETAILS
See below with code snipit which reproduces my problem, I've commented some of the
.js
to illustrate what I've tried so far.var app = angular.module('app', []); app.controller('mainController', ['$http', 'mainService', function($http, mainService){ mainCtrl = this; mainCtrl.test = "If you can see this the mainController works" var promise = mainService.getJson(); promise.then(function (data) { mainCtrl.json = data; }); }]); app.service("mainService", function ($http, $q) { var deferred = $q.defer(); /* // Method to Grab JSON that has CORs enabled: // JSON resource with CORs enabled var url = 'https://jsonplaceholder.typicode.com/posts/1'; $http({ method: 'GET', cache: true, url: url, headers: { 'Content-Type': 'application/json;charset=UTF-8' } }). success(function(response) { //your code when success deferred.resolve(response); console.log('HTTP CORS SUCCESS!'); }). error(function(response) { //your code when fails console.log('HTTP CORS ERROR!'); }); */ /* */ // Method to Grab JSON that has CORs enabled: // JSON resources without CORs enabled var url = 'http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json' // does not work? // var url = 'http://samcroft.co.uk/json-data/sample' // this one works $http({ method: 'jsonp', url: url + '?callback=JSON_CALLBACK', }). success(function(response) { //your code when success deferred.resolve(response); console.log('JSONP SUCCESS!'); }). error(function(response) { //your code when fails console.log('JSONP ERROR!'); }); this.getJson = function () { return deferred.promise; }; });
<!DOCTYPE html> <html lang="en" ng-app="app"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular-route.js"></script> <script src="app.js"></script> </head> <body ng-controller="mainController as mainCtrl"> <p>{{mainCtrl.test}}</p> <hr /> <p>You should also see the JSON obeject below:</p> {{mainCtrl.json}} </body> </html>
ORIGIONAL QUESTION DETAILS
app.controller('testController', ['$scope', '$http', function($scope, $http){ var url = 'http://example.com/getSomeJson'; $http({ method: 'JSONP', url: url, params: { format: 'jsonp', json_callback: 'JSON_CALLBACK' } }). success(function(data) { //your code when success $scope.data = data; console.log('SUCCESS!'); }). error(function(status) { //your code when fails console.log('ERROR!'); }); }]);
When I look at the json in the chromes sources panel I see where the error is highlighted.
Any idea what I'm doing wrong? Or could it be an issue with how the API service is configured?
解决方案Here you go :-)
The code you tried with the
jsonp
request looks good but the url you used is not supporting thejsonp
request, that's why you got an error.If you try the same url with
$http.get
, it will work fine.To support the
jsonp
call, the response should be wrapped with theJSON_CALLBACK ()
as belowJSON_CALLBACK ({ /* JSON */ })
Hence, I changed this to valid
jsonp
url and it worked!https://angularjs.org/greet.php?callback=JSON_CALLBACK
You can try this url in the browser and see the response, how it is wrapped with
JSON_CALLBACK ()
.But if you try the below url, you can just see the
json
without any wrapping.http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json?callback=JSON_CALLBACK
That's the difference to find whether the api supports
jsonp
.Also, I have changed the
service
below with the same syntax as in anotherSO
question answer,https://stackoverflow.com/a/41030976/7055233
Working snippet:
var app = angular.module('app', []); app.controller('mainController', ['$http', 'mainService', function($http, mainService){ mainCtrl = this; mainCtrl.test = "If you can see this the mainController works" var promise = mainService.getJson(); promise.then(function (data) { mainCtrl.json = data; }); }]); app.service("mainService", function ($http, $q) { var deferred = $q.defer(); var url = 'https://angularjs.org/greet.php'; //var url = 'http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json'; /* // Method to Grab JSON that has CORs enabled: // JSON resource with CORs enabled var url = 'https://jsonplaceholder.typicode.com/posts/1'; $http({ method: 'GET', cache: true, url: url, headers: { 'Content-Type': 'application/json;charset=UTF-8' } }). success(function(response) { //your code when success deferred.resolve(response); console.log('HTTP CORS SUCCESS!'); }). error(function(response) { //your code when fails console.log('HTTP CORS ERROR!'); }); */ /* */ // Method to Grab JSON that has CORs enabled: // JSON resource without CORs enabled function getJson() { // $http.jsonp(url + "?callback=JSON_CALLBACK"). // this does not work either $http.jsonp(url + '?callback=JSON_CALLBACK'). then(function(response) { //your code when success deferred.resolve(response); console.log('JSONP SUCCESS!'); }, function(response) { //your code when fails console.log('JSONP ERROR!'); deferred.reject(response); }); return deferred.promise; } this.getJson = getJson; });
<!DOCTYPE html> <html lang="en" ng-app="app"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular-route.js"></script> <!--<script src="app.js"></script>--> </head> <body ng-controller="mainController as mainCtrl"> <p>{{mainCtrl.test}}</p> <hr /> <p>You should also see the JSON obeject below:</p> {{mainCtrl.json}} </body> </html>
这篇关于AngularJS中带有$ http的HTTP JSONP请求问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!