[使用HttpClient向本地json文件发送POST请求

问题描述 投票:1回答:2

我在我的角度应用程序中的资产内有一个名为fake.jsonjson文件。该文件的路径是这样的。

MyApp => src =>资产=> json => fake.json

我想在应用程序文件夹内的组件中使用HttpClient向此文件发出POST请求。

MyApp => src => app =>统计=> statistics.component.ts

组件源代码

export class StatisticsComponent {

  persons: Person[];

  options = {
    sDom: 'rt<"bottom"p>',
    pagingType: 'full_numbers',
    pageLength: 10,
    serverSide: true,
    processing: true,
    ajax: (dataTablesParameters: any, callback) => {
      this.http
        .post<DataTablesResponse>(
          './../../assets/json/fake.json',
          dataTablesParameters, {}
        ).subscribe(resp => {
          this.persons = resp.data;
          callback({
            recordsTotal: resp.recordsTotal,
            recordsFiltered: resp.recordsFiltered,
            data: []
          });
        });
    },
    columns: [
      { data: "id" },
      { data: "firstName" },
      { data: "lastName" }
    ]
  };

  constructor(private http: HttpClient) {

  }

}

class Person {
  id: number;
  firstName: string;
  lastName: string;
}

class DataTablesResponse {
  data: any[];
  draw: number;
  recordsFiltered: number;
  recordsTotal: number;
}

我发生了以下错误

http://localhost:4200/assets/json/fake.json的HttpErrorResponse Http失败响应:404未找到

我对此有2个疑问。

  1. 使用Http或HttpClient向本地json文件发出POST请求是否有效。 (到目前为止,我已经使用Http而不是HttpClient完成了GET请求,并成功获取了数据)

  2. 当文件夹中存在该文件时,为什么它返回404 Not Found。

需要帮助。

angular angular-httpclient
2个回答
2
投票

这是因为您放置在assets文件夹中的任何内容都将通过GET请求提供。您可以通过在浏览器上导航至http://localhost:4200/assets/json/fake.json来测试此功能。如果要测试POST方法,则需要启动服务器。

HttpModule已被弃用,并在以后的Angular版本中删除。您应该将其更改为HttpClientModule

要使用HttpClient进行测试,可以执行以下操作。

HttpClientModule添加到您的AppModule

在组件中注入HttpClient

constructor(private httpClient: HttpClient) {}

并按如下所示进行请求

this.httpClient.get('/assets/json/fake.json',  { observe: 'body' })
    .subscribe(result => {
      console.log(result);
    });

1
投票

为了从本地JSON文件读取或写入数据,可以使用json-server。

  1. 创建fake.json文件。
  2. 安装json-server npm i json-server
  3. 启动JSON服务器json-server --watch fake.json
  4. 现在在http://localhost:3000/上请求服务器

按照文档链接:https://www.npmjs.com/package/json-server

© www.soinside.com 2019 - 2024. All rights reserved.