标签: angularjs-http

$ http拦截器中的Angular UI Bootstrap模式对话框挂起浏览器

我正在尝试实现延迟授权,只有当用户触发调用需要身份验证的API时才会引入登录对话框.我正在使用bootstrap ui.bootstrap.modal(以及模态中的ui.bootstrap.alert).问题是这些指令明确指定了以下内容teamplateUrl:

  • template/modal/backdrop.html(在modal.js 这里)
  • template/modal/window.html(在modal.js 这里)
  • template/alert/alert.html(在alert.js 这里)

像这样:

.directive('modalBackdrop', ['$timeout', function ($timeout) {
  return {
    restrict: 'EA',
    replace: true,
    templateUrl: 'template/modal/backdrop.html',
    link: function (scope, element, attrs) {
      /* ... */
    }
  };
}])
Run Code Online (Sandbox Code Playgroud)

每当我调用$modal.open()ui-bootstrap为新的模态窗口构建DOM时,angular会尝试通过$http服务解析这些URL,即使模板已经通过$templateCache.put方法或添加<script>标记加载.这基本上是在我的拦截器中引起无限递归,它试图在request上面的url的重载中引入登录对话框.

这是我的拦截器的简化版本:

.config(['$provide', '$httpProvider', function($provide, $httpProvider) {
    $provide.factory('testInterceptor', ['$injector', function($injector) {
        return {
        'request': function(config) {

            var auth = $injector.get('authService');
            var modal = $injector.get('$modal');
            if …
Run Code Online (Sandbox Code Playgroud)

angularjs angular-ui angularjs-directive angular-ui-bootstrap angularjs-http

3
推荐指数
1
解决办法
4043
查看次数

无法在Django中获取AngularJS的$ http.post数据

我知道这是一个非常基本的问题,但是在浪费了我一整天之后我都在问这个问题.我只是使用以下AngularJS代码向Django发送数据:

$http.post('/data/creation', 
                    {
                html: 'a'

            }).
              success(function(data, status, headers, config) {
                // this callback will be called asynchronously
                // when the response is available
                  console.log(data);
                  console.log(status);
                  console.log(headers);
                  console.log(config);
              }).
              error(function(data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                  console.log(status);
                  console.log(data);
              });
Run Code Online (Sandbox Code Playgroud)

在django:

@csrf_exempt
def snippets_post(request):
    html = False
    css = False
    js = False
    JSONdata = False
    response = "You're looking at the results of question %s."
    if …
Run Code Online (Sandbox Code Playgroud)

python django angularjs angularjs-http

3
推荐指数
1
解决办法
1589
查看次数

AngularJS $ http POST withCredentials失败,请求正文中包含数据

AngularJS使用REST对服务器端进行身份验证,并获取JSESSIONID cookie.在下一步中,我尝试使用REST从服务器端获取一些JSON数据以及在上一步中获得的会话cookie.这是客户端代码:

getSomeJSONDataFromServer:function() {
var deferred = $q.defer();
$http({
    method: 'POST',
    withCredentials: true,
    url: "http://domain.name/app/someURL",
    headers:{
        'Accept':'application/json',
        'Content-Type':'application/json; charset=utf-8',
        'Access-Control-Request-Headers': 'X-Requested-With, content-type, accept, origin, withcredentials'
    }
})
.success(function(data, status, headers, config) {
    // handle data
})
.error(function(data, status, headers, config) {
    // handle error
});
return deferred.promise;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常:

没有正文的CORS $ http请求

当我在上面的POST请求体中发送一些数据时,问题就开始了.

...
$http({
    method: 'POST',
    withCredentials: true,
    url: "http://domain.name/app/someURL",
    headers:{
        'Accept':'application/json',
        'Content-Type':'application/json; charset=utf-8',
        'Access-Control-Request-Headers': 'X-Requested-With, content-type, accept, origin, withcredentials'
    },
    data: '{}'
})
.success(...
Run Code Online (Sandbox Code Playgroud)

上述代码在prelight请求中失败:

CORS $ http请求与身体失败!

看起来服务器启动一个新会话,因为会话cookie由于某种原因没有发送.无论如何,我觉得我错过了一些非常简单的东西,一些标题或类似的东西...任何想法都很感激.提前致谢.

rest session-cookies cors preflight angularjs-http

2
推荐指数
1
解决办法
9884
查看次数

Angular $ http附加数据作为对象

我正在尝试使用angularjs从soundcloud API获取曲目列表.
我试图发送的参数是:
1)client_id(字符串)
2)持续时间(具有两个属性的对象).

这是代码:

    var CLIENT_ID = 'a81f01ef5d0036415431e8be76c8db0e';
    var TRACKS_URL = 'https://api.soundcloud.com/tracks.json';

    var app = angular.module('soundcloud', []);

    app.controller('tracksController', function ($scope, $http) {

        $http({
            url: 'https://api.soundcloud.com/tracks.json',
            method: 'GET',
            data: {
                client_id: CLIENT_ID,
                duration: { // in milliseconds
                    from: 300000,
                    to: 400000
                }
            }
        })
            .success(function (data) {
                $scope.trackList = data;
            })
            .error(function () { alert('error'); });
    });
Run Code Online (Sandbox Code Playgroud)

当我在broweser的调试器中检查请求时,根本无法识别这些参数.

我尝试使用'params'代替'data',但这样它将'duration'对象变为json - >然后我得到状态500作为响应.
当我只在params发送client_id时,它工作正常,因为没有对象,只有字符串.

jQuery的ajax方法工作正常:https://jsfiddle.net/oacwz1up/3/

我该怎么办 ?如何正常发送参数?
请帮忙!谢谢!

javascript angularjs angularjs-http

2
推荐指数
1
解决办法
4132
查看次数

在服务/工厂中使用$ http.get来返回集合

我尝试http.get在angularjs服务中使用promise,对获得的集合进行一些操作,最后将其返回给控制器......

我的问题是如何$http.get()在服务中使用a 来获取和操作结果,然后将其返回给控制器,如下面的代码所示: PEN代码

var app = angular.module('myApp', []);

app.controller('customersCtrl', ['$scope','customer',function($scope, customer) {
  $scope.odds = customer.odds;
}]);

app.factory('customer', ['$http', function($http) {
  var all = [{'Id':88, 'Name':"A"}, {'Id':89, 'Name':"ShoutNotBeHere"}]; 
  var odds = [];

  $http.get("http://www.w3schools.com/angular/customers.php")
    .then(function(response) {
      all = response.records;
    });

  angular.forEach(all, function(c, i) {
    if (i % 2 == 1) {
      odds.push(c);
    }
  });

  return {odds: odds};
}]);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
  <div ng-app="myApp" ng-controller="customersCtrl">
    Odd ids from www.w3schools.com/angular/customers.php
    <ul>
      <li ng-repeat="c in odds">
        {{ c.Id …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs angularjs-factory angularjs-http angular-promise

2
推荐指数
1
解决办法
1万
查看次数

PDF Javascript Blob中的非UTF-8字符

我有一个PDF文件,我从WebApi 2应用程序提供给AngularJS客户端.我使用文件保护程序然后将文件保存在客户端上,如下所示(在TypeScript中):

   this.$http.get(`${webUrl}api/pdf?id=${fileDto.id}`)
    .then((response: ng.IHttpPromiseCallbackArg<any>) => {
        var file = new Blob([response.data], { type: 'application/pdf' });
        saveAs(file, 'my.pdf');
    });
Run Code Online (Sandbox Code Playgroud)

我这样做的原因是我可以使用持票人令牌来授权访问PDF(这是通过拦截器添加的).这适用于PDF文件包含非UTF8字符的情况.在后一种情况下,文件仍然会下载,但是当我打开它时,它显示为空白.打开文件我可以看到非UTF8字符被替换为□字符.在JavaScript中,当我检查response.data调试器中的字符串值时,我看到这些字符由represented表示.我是否正确地假设,因为文件是用JavaScript中的字符串编写的,无论我做什么,我都无法正确保存来自JavaScript的非UTF8字符的文件?

pdf blob utf-8 angularjs angularjs-http

2
推荐指数
1
解决办法
1293
查看次数

多个返回的密钥json

我有一个运行k2的joomla网站,并通过在字符串末尾添加format = json来从中提取信息:https://www.example.com/posts? format = json ,输出如下内容:

{
site: {
      url: "https://www.example.com",
      name: "mySite"
      },
category: {
          id: "67",
          name: "Gauteng",
          alias: "gauteng",
          link: "/tna/provincial/gauteng.html",
          parent: "66",
          extraFieldsGroup: "0",
          image: null,
          ordering: "1",
        events: {
          K2CategoryDisplay: ""
        },
        chidlren: []
       },
items: [{ 
         id="1",
         title="The Title",
         body="body content here..."
        },
        { 
         id="2",
         title="The Title",
         body="body content here..."
        }
}
Run Code Online (Sandbox Code Playgroud)

现在我正在为此创建一个服务,只想访问"项目".

.factory('Posts', function($http) {

  var posts = [];

  return {
        getPosts: function(){
            return $http.get("https://www.example.com/posts?format=json").then(function(response){
                posts = response;
                return …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs angularjs-factory angularjs-http ionic-framework

1
推荐指数
1
解决办法
54
查看次数

Angular Service/Controller没有回复承诺?

所以我终于让我的应用程序工作到它获得JSON请求的正确URL.但是现在我无法使用该URL.

我知道该服务正在从Google Maps API返回承诺,我可能不应该这样做,但如果我将其删除,我会收到"Weather.getWeather is undefined"错误.我不知道为什么.

我怎样才能让它正常工作.谢谢你的帮助.

weatherService.getWeather = function(city)  {


        var coordsUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + city;


        return $http.get(coordsUrl)
            .success(function(data) {
                var coords = data.results[0].geometry.location.lat + ',' + data.results[0].geometry.location.lng;

            return getWeatherData(coords);  

        }); 

function getWeatherData(coords)  {
            var deferred = $q.defer(),
            apiKey = 'cbbdddc644184a1d20ffc4a0e439650d',
            weatherUrl = 'https://api.forecast.io/forecast/' + apiKey + '/' + coords + '?callback=JSON_CALLBACK';


            $http.jsonp(weatherUrl)
                .success(function(data) {

                    deferred.resolve(data);

                }).error(function(err) {

                    deferred.reject(err);

                });

            console.log(weatherUrl);

            return deferred.promise;
        }        

    };
Run Code Online (Sandbox Code Playgroud)

控制器:

vm.fetchWeather = function(city) {

    Weather.getWeather(city)
        .then(function(data) {
            console.log(data);
            vm.place = data;
    });
};
Run Code Online (Sandbox Code Playgroud)

javascript promise angularjs angularjs-http angular-promise

1
推荐指数
1
解决办法
250
查看次数

是否有可能在另一个请求中有一个Angular js $ http请求?

我正在尝试发送请求AngularJS以获取用户注册的令牌.一旦我获得令牌,我将使用令牌发送另一个请求来注册用户.

但是第一个请求有效,我得到令牌,但第二个请求不起作用.

facebookExample.controller('registerController', function($scope, $http, $localStorage, $location) {
  $scope.data = {};
  $scope.getToken = function() {
      $http.post('http://you-serve.org/api.php?action=createaccount&format=json&name=' + $scope.data.username + '&email=' + $scope.data.email + '&realname=' +
        $scope.data.firstname + ' ' + $scope.data.lastname +
        '&mailpassword=false&reason=Fun_and_profit&language=en&token').then(
        function(response) {
          return response.data.createaccount.token;
        }
        // End success
        ,
        function() {
          alert('error');
        } // End error 
      ); //End then
    } // End getToken

  $scope.register = function(myToken) {
      $http.post('http://you-serve.org/api.php?    action=createaccount&format=json&name=' +
        $scope.data.username + '&email=' +
        $scope.data.email + '&realname=' +
        $scope.data.firstname + ' ' +
        $scope.data.lastname …
Run Code Online (Sandbox Code Playgroud)

html javascript http angularjs angularjs-http

1
推荐指数
1
解决办法
3038
查看次数

Angular $ http没有处理错误

我的角度应用程序不处理$ http调用中的错误.

我有一个$httpProvider$q.reject(response)在errorResponse中返回的文档所需的位置.在控制台中角度刚刚放置angular.min.js:99 GET http://localhost:8080/my/api 500 (Internal Server Error).

console.log('before');
$http.get('/my/api', function(response){
   console.log('ok');
   console.log(response);
}, function(response){
    console.log('not ok');
    console.log(response)
});
console.log('after');
Run Code Online (Sandbox Code Playgroud)

我只是得到'之前','之后'和上面的信息.

同样在网络选项卡中,我从服务器获得预期响应,状态为500,正文中包含json内容.

除了没有返回$ q.reject()的$ httpProvider的errorResponse,可能是什么问题?

asynchronous promise angularjs angularjs-http angular-promise

1
推荐指数
1
解决办法
417
查看次数

获取响应为"data":null,"status": - 从AngularJS调用web api时为1

我试图从Angular JS 1.6.0调用Web API GET方法并得到以下错误: -

可能未处理的拒绝:{"data":null,"status": - 1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam" :"callback","url":" http:// localhost:51972/api/video ","headers":{"Accept":"application/json,text/plain,/ "}},"statusText": ""}

当我从Fiddler 4调用相同的GET方法并返回JSON Text时,我得到了正确的JSON响应.

请注意,我的WEB API和Angular JS代码位于不同的目录中.

根据Dez的评论,我修改了WebApiConfig.cs以从WebAPI返回JSON响应

WebApiConfig.cs

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }
    }
Run Code Online (Sandbox Code Playgroud)

VideoController.cs

public class VideoController : ApiController
{
        [Route("api/video")]
        public List<VideoViewModel> GetVideo()
        {
            List<VideoViewModel> video = new List<VideoViewModel>();
            video.Add(new VideoViewModel { Name = …
Run Code Online (Sandbox Code Playgroud)

asp.net-web-api angularjs angularjs-http

0
推荐指数
1
解决办法
5678
查看次数