You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular代码抛出[$http:badreq]错误,请求协助排查原因

排查Angular $http获取JSON数据失败的问题

我帮你梳理了代码里的问题,新手刚接触Angular时很容易犯这类小错误,咱们一步步解决:

1. 致命拼写错误:URL变量名写错了

你代码里定义的是this.basrUrl(注意是s),但在$http请求里用的是self.baseUrl(这里是e),这直接导致请求的URL变成undefined,肯定会失败!把this.basrUrl改成this.baseUrl就能解决这个核心问题。

2. 确认是否调用了加载方法

就算修正了拼写,如果没触发loadAllMatches函数,数据也不会主动加载。你可以选择两种方式:

  • 在模板里加个触发按钮:<button ng-click="main.loadAllMatches()">加载比赛数据</button>(假设你用了controller as语法)
  • 或者在控制器初始化时直接调用:在控制器最后加一行self.loadAllMatches();,页面加载时自动获取数据

3. 验证返回数据结构(可选但建议)

虽然目标JSON的结构确实是顶级对象包含matches数组,但如果后续还是有问题,建议在success回调里先打印response.data,确认返回的数据格式和你预期的一致,避免因为数据结构变化导致赋值失败。

修正后的完整代码

var app = angular.module('mainApp', []);
app.controller('mainController', ['$http', function ($http){
    var self = this;
    this.matches = [];
    console.log(this.matches);
    // 修正拼写错误:basrUrl → baseUrl
    this.baseUrl = "https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.json";
    this.loadAllMatches = function(){
        $http({
            method: "GET",
            url: self.baseUrl,
        }).then(function successCallback(response){
            console.log(response);
            // 确认数据结构后再赋值
            console.log('返回的完整数据:', response.data);
            self.matches = response.data.matches;
            console.log('赋值后的matches:', self.matches);
        },function errorCallback(response){
            alert("Some Error occurred, check the console");
            console.log('错误详情:', response);
        });
    }
    // 可选:页面加载时自动调用
    // self.loadAllMatches();
}]);

配套模板示例(如果还没写的话)

<div ng-app="mainApp" ng-controller="mainController as main">
    <button ng-click="main.loadAllMatches()">加载比赛数据</button>
    <div ng-if="main.matches.length > 0">
        <h3>比赛列表</h3>
        <ul>
            <li ng-repeat="match in main.matches">
                {{match.home_team}} vs {{match.away_team}} | 比分:{{match.score.full_time.home}}-{{match.score.full_time.away}}
            </li>
        </ul>
    </div>
</div>

最后提醒下:新手排查Angular问题一定要习惯打开浏览器控制台(按F12),里面会明确显示错误信息,比如这次的拼写错误会提示baseUrl is undefined,能帮你快速定位问题。

内容的提问来源于stack exchange,提问作者Abhinav Alok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:02:44