Sawdust
Sawdust

Reputation: 115

fetch() post 404 error

I'm writing a simple preact front end for a node.js app. I am trying to read data from a json file in my project directory, take some input from the user, then write it back to the file.

I can load the json file from my project directory using fetch()...

fetch('config.json');

... however when I come to write data back into the file, I get a 404...

fetch('config.json', {
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
    },
    method: 'POST',
    body: JSON.stringify(this.state)
});

Any ideas why this doesn't work?

Upvotes: 2

Views: 2898

Answers (1)

emilyb7
emilyb7

Reputation: 186

A post request needs to be handled by your server, so you can't just post directly to a file.

If you're using Express, you can create a route for this. Something like:

app.post('/post-data', function(request, response){
  // get data and write to the file here
})

See: http://expressjs.com/en/api.html#app

Upvotes: 2

Related Questions