【问题标题】:Why do I keep getting a 404 not found when using $http.get() on local server?为什么在本地服务器上使用 $http.get() 时总是找不到 404?
【发布时间】:2017-05-12 02:45:04
【问题描述】:

我是 Angular js 的新手。我使用的是 1.6 版。

我正在尝试使用工厂从本地 json 文件中读取数据以显示信息。我不断收到此错误:

plotFactory.getPlots(...).then(...).error 不是函数

我的本​​地文件结构是

App/scripts/data/plots.json

App/scripts/app.js

App/scripts/main.controller.js

App/scripts/plot.factory.js

App/index.html

main.controller.js

angular
    .module('myApp')
    .controller('mainController',function ($scope, $http, plotFactory) {

        $scope.plots = [];

        //Method 1
        plotFactory.getPlots().then(function successCallback (resp) {
            console.log("If you reading this , momma we made it.")
            $scope.plots = resp.data;
        }).error(function (error) {
            console.log(error)
        });

    });

plot.factory.js

angular
.module('myApp')
.factory('plotFactory', function($http) {

    function getPlots() {
        return $http.get('data/plots.json');
    }

    return {
        getPlots: getPlots
    }
});

index.html

<body ng-app="myApp" ng-controller="mainController">

    <a class="accessibility" href="#main-content" accesskey="S">Skip to Content</a>
    <div class="loading-screen">
        <img src="_assets/images/pentair_logo.png" width="359" height="100" alt="Emerson" />
    </div>
    <div id="wrapper">
        <header>
            <div class="container-fluid">
                <a href="#" class="logo"><img class="logoimg" src="_assets/images/pentair_logo.png" alt="Pentair" /><span>Interactive Sales Presentation</span></a>
                <a href="#" class="menu-opener pull-right"><span></span></a>
            </div>
        </header>
        <div class="menu-wrapper">
            <div class="mobile-menu">
                <ul class="collapsible">
                    <li ng-repeat="mobileMenu"><a href={{mobileMenu.url}}>{{mobileMenu.name}}</a></li>
                </ul>
            </div>
        </div>

        <div class="main-content">
            <div class="container-fluid">
                <div class="content-wrapper">
                    <img src="_assets/images/ui/Main_Background_edit.jpg" class="map-overlay" width="1024" height="768" alt="Oil and Gas" />
                    <div class="map-wrapper">
                        <div class="map-control level-01 panzoom">
                            <img src="_assets/images/ui/Main_Background_edit.jpg" class="map-bg" width="1024" height="768" alt="Oil and Gas" />
                            <div class="overlay"></div>

                            <!-- All Map Points -->
                            <div ng-repeat="plot in plots">
                                <a href={{plot.url}} class="plot level1 arrow-head flip {{plot.sid}}"><div><span class="title">{{plot.name}}</span><span class="number">+</span></div></a>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </div>

        <footer>
            <div class="container-fluid">
                Footer
            </div>
        </footer>

    </div>


    <!-- Load Angular Dependencies -->


    <!-- Async load of Javascript  -->
    <script type="text/javascript">
        function loadJS(e) { var t = document.createElement("script"); t.type = "text/javascript", t.async = !0, t.src = e; var n = document.getElementsByTagName("head")[0]; n.appendChild(t) };
        loadJS('_assets/js/all.min.js');
    </script>

    <!-- In case javascript is disabled -->
    <noscript>
        <script type="text/javascript" src="_assets/css/all.min.js"></script>
    </noscript>

    <!-- Main App -->

    <script type="text/javascript" src="Angular/angular.min.js"></script>

    <script src="Angular/angular-route.min.js"></script>
    <script src="scripts/app.js"></script>

    <script src="scripts/plot.factory.js"></script>
    <script src="scripts/main.controller.js"></script>

</body>

我尝试了几种不同的路径,但都不起作用。但是,如果我将 json 数据作为变量留在工厂内,我的数据将被读取……但我正在尝试将数据与控制器分开以进行良好实践。我的猜测是该函数导致错误:不是函数,因为路径未返回任何有效内容,因此提示 .then 函数失败。是我工厂$http.get() 请求中的文件路径吗?还是我错过了其他东西?


更新了 get 函数和回调。

plotFactory.getPlots().then(function successCallback(response) { 
    //this callback will be called asynchronously
   //when the response is available 
   $scope.plots = response.data;
   console.log("Method 2 worked!") 
},function errorCallback(response) { 
   console.log("We got a problem...") 
}); 

仍然找不到data/plots.json 的 404。 这可能是参考错误吗?

【问题讨论】:

  • “不是一个函数,因为路径没有返回任何东西”,不,它给出了那个错误,因为不再有 error() 角度承诺的函数。使用格式看documentation
  • @PatrickEvans 谢谢。我更新了 get 函数和回调。 plotFactory.getPlots().then(function successCallback(response) { //这个回调将被异步调用 //当响应可用时 $scope.plots = response.data; console.log("方法 2 成功了!") } , function errorCallback(response) { console.log("We got a problem...") });仍然得到 404 not found for data/plots.json 。这可能是参考错误吗?

标签: javascript angularjs http get


【解决方案1】:

问题在于您的文件路径。如果您在本地服务器中运行应用程序,请正确提及路径。假设您在 localhost 端口 3000 中运行,它应该是这样的:

$http.get("localhost:3000/myApp/data/plots.json");

或者,如果您在浏览器中打开 index.html 并对其进行测试(虽然在 Chrome 中不起作用,但在 FireFox 中起作用),请提及控制器文件中 json 文件的路径,例如:

$http.get("../data/plots.json")

假设它位于“脚本”文件夹所在的同一文件夹中。

【讨论】:

    【解决方案2】:

    浏览器内 JavaScript 的 URL 是相对于运行脚本的 HTML 文档的 URL 进行解析的,而不是针对脚本本身的 URL。

    由于 HTML 文档位于 App/index.html,因此您需要 scripts/data/plots.json,而不是 data/plots.json

    (这假设 Angular 没有使用 History API 来更改 URL)。

    【讨论】:

    • 谢谢。仍然得到404。我的请求如下所示: $http({ method: 'GET', url: '/scripts/data/plots.json' }) 控制台错误是: GET localhost:51998/scripts/data/plots.json 404 (Not Found) 也许原点是错误的?或者使用绝对路径?
    • @AdanHuerta — 你使用的是什么 HTTP 服务器?
    【解决方案3】:

    仍然找不到data/plots.json 的 404。这可能是参考错误吗?

    使用scripts/data/plots.json

    同时使用.catch 代替.error

    欲了解更多信息,请参阅Why are angular $http success/error methods deprecated? Removed from v1.6?

    【讨论】:

      【解决方案4】:

      感谢您的意见。原来这个解决方案有两个部分,一个是文件路径。

      第 1 部分:

       return $http({
                      url: "/scripts/data/plots.json",
                      method: 'GET'            
                  })
      

      使用正确的路径。

      第 2 部分:对我来说比较棘手。我很抱歉没有在问题中包含这个。我正在使用 Visual Studio 2013,它使用需要设置为允许某些类型的 JSON 文件的 Web.config 文件。在我的高级开发人员指出之前,我不知道。我会记住这一点以备将来查询。

      再次感谢 !

          <?xml version="1.0"?>
      
      <!--
        For more information on how to configure your ASP.NET application, please visit
        http://go.microsoft.com/fwlink/?LinkId=169433
        -->
      
      <configuration>
      
          <system.web>
            <compilation debug="true" targetFramework="4.5" />
            <httpRuntime targetFramework="4.5" />
      
          </system.web>
      
        **<system.webServer>
          <staticContent>
            <mimeMap fileExtension=".json" mimeType="application/json" />
          </staticContent>
        </system.webServer>**
      
      </configuration>
      

      【讨论】:

        猜你喜欢
        • 2015-08-29
        • 1970-01-01
        • 1970-01-01
        • 2011-05-27
        • 1970-01-01
        • 2023-04-08
        • 2014-05-10
        • 2016-10-24
        • 2015-07-22
        相关资源
        最近更新 更多