【问题标题】:$http:badreq - GET json Object$http:badreq - 获取 json 对象
【发布时间】:2017-03-14 09:23:54
【问题描述】:

我想发出一个$http 请求使用配置对象而不是快速方法。请求是 'GET' 方法,并且 url 以本地 json 文件为目标。

代码看起来或多或少像:

$http.get({
    method: 'GET',
    url: 'data.json'
  }).then(function(res) {
    $scope.data = res;
  }, function(res) {
    console.log(res);
  })

我得到的错误是:

错误:[$http:badreq]

这是一个“工作”plunker 演示问题。

事实是,如果我使用快速方法$http.get('clients.json'),它就可以工作。

任何帮助将不胜感激。

【问题讨论】:

    标签: angularjs json http


    【解决方案1】:

    更新您的 app.js 文件

    var app = angular.module('app', []);
    
    app.controller('MainCtrl', function($scope, $http) {
      $http({
        url: 'data.json',
        type: 'GET'
      }).then(function(res) {
        $scope.data = JSON.stringify(res.data);
      }, function(res) {
        console.log(res);
      })
    });
    

    DEMO

    【讨论】:

    • 我已经提到了两次我不想使用快捷方式。但是配置对象。
    • 我认为你使用了两次 get 类型。将 get 从 $http.get({ 更改为 $http({
    • 哦,有人瞎了。非常感谢!
    • 很高兴为您提供帮助
    【解决方案2】:

    试试这个它对我有用:plunker

    app.controller('MainCtrl', function($scope, $http) {
      $http({method: 'GET',url : './data.json'}).then(function(res) {
        $scope.data = res;
      }, function(res) {
        console.log(res);
      })
    });
    

    【讨论】:

    • 我已经提到了两次我不想使用快捷方式。但是配置对象。
    【解决方案3】:

    首先在您的index.html 上,您使用{data}} 而不是:

    <body ng-controller="MainCtrl">
        {{data}}
    </body>
    

    在您的控制器上,您必须按以下方式调用$http(不使用$http.get,而只是使用$http):

    $http({
      method: 'GET',
      url: 'data.json'
    }).then(function successCallback(response) {
      $scope.data = response.data;
    }, function errorCallback(response) {
      console.log(response);
    });
    

    在此处查看工作更新https://plnkr.co/edit/OCPkPYsbcHv2snef5Bj3?p=preview

    【讨论】:

      【解决方案4】:

      看来你的代码是错误的,你已经使用了 $http.get,但仍然添加 {method: 'GET'}。

      我猜你想直接使用 $http 请求。

      $http({ method: 'GET', url: 'data.json' }).then(function(res) { $scope.data = res; }, function(res) { console.log(res); })

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-15
        • 2013-09-24
        • 1970-01-01
        • 1970-01-01
        • 2022-11-27
        • 2022-01-24
        相关资源
        最近更新 更多