Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST request to a local json file using HttpClient

I have one json file named fake.json inside assets in my angular application. Path of this file is like this.

MyApp => src => assets => json => fake.json

I want to make a POST request to this file using HttpClient in my component which is in inside app folder.

MyApp => src => app => Statistics => statistics.component.ts

Component source code

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;
}

I occurred this following error

HttpErrorResponse Http failure response for http://localhost:4200/assets/json/fake.json: 404 Not Found

I got 2 doubts over this.

  1. Is it valid to make a POST request to a local json file using Http or HttpClient. (Till now I have done GET request using Http not HttpClient and got the data successfully)

  2. Why it returns 404 Not Found when the file is present there inside the folder.

Need Help.

like image 401
Rishikesh Dehariya Avatar asked Sep 20 '25 06:09

Rishikesh Dehariya


1 Answers

It's because whatever you put inside assets folder will be served via GET requests. You can test this by simply navigation to http://localhost:4200/assets/json/fake.json on browser. If you want to test POST method, you need to start a server.

HttpModule is deprecated and removed in later versions of Angular. You should change it to HttpClientModule

To test it with HttpClient, you can do the following.

Add HttpClientModule to your AppModule

Inject HttpClient within your component

constructor(private httpClient: HttpClient) {}

And make the request as follows

this.httpClient.get('/assets/json/fake.json',  { observe: 'body' })
    .subscribe(result => {
      console.log(result);
    });
like image 111
Bunyamin Coskuner Avatar answered Sep 21 '25 23:09

Bunyamin Coskuner