【问题标题】:Http request to local json file not working对本地 json 文件的 Http 请求不起作用
【发布时间】:2019-04-04 04:49:45
【问题描述】:

我有一个非常简单的应用程序,我想使用 http get 请求显示产品列表。我正在调用位于以下位置的本地 json 文件:

但是,我收到以下错误:

服务器返回代码 404,错误信息为:http://localhost:4200/api/products/products.json 的 Http 失败响应:404 Not Found

这是我的服务的快照:

如您所见,我已经指定了产品 url,并且使用这个 productURL,我正在使用 httpGet 来获取产品列表,但是这个请求失败了,因为说服务无法找到 products.json。

我的 angular.json 的快照

对可能是什么问题有任何见解吗?

提前致谢

【问题讨论】:

  • buildangular.json注册你的api文件夹assets就像app/api/product一样
  • api文件夹已经注册在assets下。它是这样注册的:“src/api”
  • 您需要将此添加到您的 angular.json 中。在 src 中只有文件夹不会在资产下注册。您需要明确告诉 Angular 在构建时使用产品文件夹中存在的 json。所以在angular.json 中你需要在build --> assets 对象中再添加一个条目
  • 请分享您的angular.json
  • 我在原始查询中添加了一个快照。我已经按照你的方法试过了,它仍然没有显示产品列表

标签: angular


【解决方案1】:

在 angular.json 中注册你的 api 文件夹

...
"build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets",
              "src/app/api/products" // Forgot to add app here..now chk if its working
            ],
            "styles": [
              "src/styles.scss",
              "src/montserrat/montserrat.scss"
            ],
            "scripts": [

            ]
             ...

确保在对 angular.json 进行更改后重新启动服务器

else 在项目的 assets 文件夹中添加 API 文件夹 演示:https://stackblitz.com/edit/angular-jvascy

【讨论】:

  • @MahadevanSwamy 尝试将您的 api 文件夹移动到 assets 文件夹中...然后使用类似 assets/api/products/products.json 的路径
  • 请查看添加的 stackblitz URL
猜你喜欢
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-05
  • 1970-01-01
相关资源
最近更新 更多