如何从JSONP错误回调数据angularjs? [英] How to get data from JSONP error callback in angularjs?

查看:182
本文介绍了如何从JSONP错误回调数据angularjs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在angularjs从JSONP错误回调得到响应消息,但响应的数据是不确定的。我回用409 HTTP code的响应。如果直接在浏览器中打开URL JSONP显示angular.callbacks._0({消息:重置链接是不正确}),但我不能得到错误回调此消息。我在做什么错了?

  //延长API请求角应用
app.factory(用户,函数($ HTTP){    变种用户=函数(数据){
        angular.extend(此,数据);
    };    //发送链接,密码重置,以输入的电子邮件
    User.reset_password =功能(){
        返回$ http.jsonp(jsonp_url +'用户名/ reset_pass _method =讯息&放大器; user_key ='+ user_key +'和;回调= JSON_CALLBACK');
    };    返回用户;
});
app.controller('ResetPasswordController',功能ResetPasswordController($范围,用户){    $ scope.submit =功能(){        变种响应= User.reset_password();        response.then(功能(数据){
            //成功回调
        },功能(数据){
            //错误回调
            的console.log(数据)//输出:{配置:{...}数据:未定义}
        });
    }});


解决方案

随着布兰登说这蒂利是不可能从HTTP错误code JSONP响应获取数据。如果你想反正得到错误信息,你需要发送类似这样{结果:假消息:发生错误...'}与好的HTTP code,例如200

I am trying to get response message from jsonp error callback in angularjs, but response data is undefined. I return the response with 409 http code. If to open jsonp url directly in browser it shows "angular.callbacks._0({"message":"Reset link is incorrect"})", but I can't get this message in error callback. What am I doing wrong?

// Extend angular app for api requests
app.factory('User', function($http) {

    var User = function(data) {
        angular.extend(this, data);
    };

    // Send link for password reset to entered email
    User.reset_password = function() {
        return $http.jsonp(jsonp_url + 'user/reset_pass?_method=post&user_key=' + user_key + '&callback=JSON_CALLBACK');
    };

    return User;
});


app.controller('ResetPasswordController', function ResetPasswordController($scope, User){

    $scope.submit = function() {

        var response = User.reset_password();

        response.then(function(data){
            //Success callback
        }, function(data){
            // Error callback
            console.log(data) // Output: {config : {...}, data: undefined}
        });
    }

});

解决方案

As said Brandon Tilley it is not possible to get data from jsonp response with http error code. If you want anyways to get error message you need to send something like this {result: false, msg: 'Error occured...'} with "good" http code, for example 200.

这篇关于如何从JSONP错误回调数据angularjs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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