0

I'm trying to write a file by passing it as a json string to an ExpressJS POST:

app.post('/filewrite/', (req, res) => {
  const fs = require('fs');
  console.log(req.body);
  fs.writeFile("./db/test.json", req.body, function(err) {
      if(err) {
          return console.log(err);
      }  
      console.log("The file was saved!");
  }); 
});

But when I'm trying to pass, it turns up a 404:

POST http://localhost:5000/filewrite/%7B%22db%22:[%7B%22ID%22:%2211111111%22,%22job%22:%2222222222]%7D 404 (Not Found)

How do I need to define the POST route to accept parameters?

lte__
  • 7,175
  • 25
  • 74
  • 131

2 Answers2

0

If you want the data to appear in req.body, then you need to pass it in the body of the request, not in the URL.

Since you are trying to pass it in the URL, the route doesn't match.

I've no idea what piece of software POST represents, but to do this with cURL you would:

curl --header "Content-Type: application/json" \
     --request POST \
     --data '{"db":[{"ID":11111111,"job":22222222]}' \
     http://localhost:5000/filewrite/
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

You should not be passing the data in params but if you want to, here's how you can

app.post('/filewrite/:data', (req, res) => {
  const fs = require('fs');
  console.log(req.body);
  fs.writeFile("./db/test.json", req.params.data, function(err) {
      if(err) {
          return console.log(err);
      }  
      console.log("The file was saved!");
  }); 
});

Also you cannot write the data into a local file through server, you will have to set the static path for the folder or file, Save post data in local file

AZ_
  • 3,094
  • 1
  • 9
  • 19