Angularjs remove line of response data before JSON eval

荒凉一梦 提交于 2019-12-11 06:59:25

问题


I am having a serious issue with Angularjs and jQuery with this particular REST API. I am not in the same domain as said API, and can get the data back, however I am getting a "SyntaxError: invalid label "name" :{" error.

If I were to do something like $http.get or $.get I get a timeout after 10 seconds. However, if I use jsonp with either library I will see in Firebug that the data is returned in the net tab, however I get the error above in the console tab. After doing some research, I have seen plenty of people having issue with the API (a Jive product) and this specific line of text that is returned along with the JSON. The response looks something like this:

throw 'allowIllegalResourceCall is false.';
{"name":{ "givenName": "xxx"}}

The big problem is the first "throw" line. I have tried a bunch of ways to remove that line but I haven't found the proper way to do it. I apologize for not being able to provide a code sample, but if there is any way to get this work in Angularjs or jQuery, I will take it. I don't know if the answer lies in Angularjs interceptors, or transformResponse.

Any help that can be provided will be appreciated.

Thank you


回答1:


AngularJs allows you do define the methods for transforming the http response data (so you can remove the first line of the response data). You can do this either for a single request or add a httpInterceptor.

Single request:

$http.get('...', {
    transformResponse: $http.defaults.transformResponse.unshift(function(data) {
        // Remove first line of response
        data.split("\n").slice(1).join("\n")
    }
});

HttpInterceptor

.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push(function() {
      return {
        'request': function(config) {
          config.transformResponse.unshift(function(data) {
            return data.split("\n").slice(1).join("\n")
          })
          return config;
        }
      }
    })
}])

Plunker: http://plnkr.co/edit/6WCxcpmRKxIivl4yK4Fc?p=preview



来源:https://stackoverflow.com/questions/30548990/angularjs-remove-line-of-response-data-before-json-eval

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