如何从aurelia框架中的JSON文件中获取数据?

时间:2019-04-25 10:26:59

标签: aurelia aurelia-framework

我正在尝试使用aurelia-fetch-client从外部JSON文件中获取数据,但它给出了404 not found错误。

我已经尝试实现官方文档建议的基本设置。

这是我的代码:

import {HttpClient } from 'aurelia-fetch-client';

let httpClient = new HttpClient();
export class ChangeRequest {
constructor(){
  httpClient.fetch('sample.json')
    .then(response => response.json())
    .then(res => {
      console.log(res);
 }
}
}

我应该获取JSON数据的结果,但是出现以下错误:

error

这是我的文件夹结构,它是使用aurelia-cli

创建的

您可以看到sample.json位于src文件夹中,而我尝试将其放入src/Assets文件夹中但结果相同。

2 个答案:

答案 0 :(得分:3)

鉴于您正在使用Webpack,您有两种选择:

  • 将文件保留在src目录中,并使用require语句加载文件
  • 将文件移动到static文件夹并使用fetch加载。

以下是两个示例的屏幕截图:

Screenshot showing using both require and fetch for loading a json file

以及源代码:

export class App {
  async attached() {
    const importedData = require('./in-src.json');

    const fetchedData = await fetch('in-static.json')
      .then(response => response.json());

    console.log('JSON loaded via import', importedData);
    console.log('JSON loaded via fetch', fetchedData);
  }
}

最后,运行应用程序时的控制台:

enter image description here

答案 1 :(得分:2)

它为您提供404的原因是开发Web服务器没有该文件,因为您可以看到它试图从以下位置获取文件:http://localhost:8080/sample.json

您可以做的是确保将其放入开发服务器,方法可能是将其与资源(例如图像)放在同一文件夹中。如果您使用的是aurelia-cli,也许也可以将其放入dist文件夹中。