问题
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.
Is it valid to make a
POSTrequest to a local json file using Http or HttpClient. (Till now I have doneGETrequest using Http not HttpClient and got the data successfully)Why it returns 404 Not Found when the file is present there inside the folder.
Need Help.
回答1:
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);
});
回答2:
In order to read or write data from a local JSON file, you can use json-server.
- Create fake.json file.
- Install json-server
npm i json-server. - Start the JSON Server
json-server --watch fake.json. - Now request the server on
http://localhost:3000/
Follow the documentation link: https://www.npmjs.com/package/json-server
来源:https://stackoverflow.com/questions/54879355/post-request-to-a-local-json-file-using-httpclient