2

I'm trying to send a post request to a json file in typescript, Angular with HttpClient. However, I get a 404 not found error, saying it cannot fine the file results.json. I find this weird because the get requests all work perfectly fine. Currently I'm using Angular 15.

I tried the following:

    let emptyObject = {};

    const headers = new HttpHeaders()
    .set('Content-Type', 'application/json');

    this.http.post('/assets/results.json', emptyObject, {headers})
    .subscribe((res:any) => {
        console.log(res);
    }, error => {
        console.log(error)
    });

The file results.json is empty and just looks like this:

[ ]

When executing the function it says:

HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: 'Not Found', url: 'http://localhost:4200/assets/results.json', ok: false, …}

I know the file exists and the filepath works because I use the same one for get requests. Is there maybe an option I need to enable or disable? It should be possible right?

1 Answer 1

2

You need something like json-server or some server to handle the post request. A get request is just like your browser it just gets a resource from a specific URL, a POST request cannot just POST data to some file it has to be handled by a server. For a quick way to set this up for development the npm package json-server is really nice if you don't have any experience yet with setting up server: https://www.npmjs.com/package/json-server

Some extra documentation about how REST works if you are interested: https://www.codecademy.com/article/what-is-rest

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.