$http.get请求json文件总是返回404错误。

5

我希望在我的应用程序中添加一个配置JSON文件。
我已经将它添加到我的项目中,并尝试使用$http.get获取它:

$http.get('http://localhost/myProject/content.json').success(function (data) {
        // Do stuff...
}).error((data, status, headers, config) => {
        // Failure...
});

问题在于每次我都会遇到404错误。

那是因为文件不存在,请尝试直接在浏览器中输入该地址 http://localhost/myProject/content.json - Benjamin Gruenbaum
文件在那里,当我按照Erez在他的回答中所说的将其更改为txt时,它起作用了。 - Yaniv
4个回答

7

这是由于您的Web服务器mime类型配置出现问题——它可能没有为json设置任何mime类型。 尝试将文件扩展名更改为.txt或.html,应该可以解决问题。

您还可以将mime类型扩展名添加到服务器中。对于IIS express,它是web.config。例如:

 <staticContent>
    <remove fileExtension=".json" />
    <mimeMap fileExtension=".json" mimeType="application/json" />
  </staticContent>

谢谢,另一个选项是进入IIS管理器并配置它以了解MIME类型中的JSON。 - Yaniv

0
<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>


This works fine.. as what Erez A. Korn has said.

0
将 content.json 文件放在 index.html 的同级目录中并使用以下内容:
$http.get('content.json').success(function (data) {
        // Do stuff...
}).error((data, status, headers, config) => {
        // Failure...
});

0
在 Angular 4 中,将 .json 文件存储到项目的根目录中。所有的 Json 文件都应该存储在同一个文件夹中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接