$ http:badreq - GET json对象

时间:2017-03-14 09:23:55

标签: angularjs json http

我想要$http请求使用配置对象而不是快速方法。请求是' GET'方法和网址以本地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'),它就会起作用。

任何帮助都将不胜感激。

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

试试这个对我有用:plunker

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

答案 2 :(得分:0)

首先在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

答案 3 :(得分:0)

似乎您的代码错误,您已经使用$ http.get,但仍然添加{method:'GET'}。

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

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

相关问题