javascriptexpressserverlocalhost

javascript express body has no contents


My problem is that req.body is returning 'Object'. In the code below I get the TypeError message. The 'req' variable seems to contain nothing.

First, this is my curl testing command. I would like 'here-again' to show up in the file '/home/dave/test.txt'. I have tried putting 'here-again' in quotes.

curl -X PUT http://localhost:8008/config/ --data here-again

Below is my js code.

app.put('/config/',  function (req, res)  {
    const filename = '/home/dave/test.txt';
    const data = req.body;
    //res.send('body ' + data + ' ' + filename );
    console.log(data)
    fs.writeFile(filename, data, (err) => {
    if (err) {
        console.error(err);
        res.status(500).send('Error writing file');
    } else {
        res.send('Data saved successfully');
    }
  });
  // 
})

Below is my error message.

TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of Object


Solution

  • The problem is due to req.body being undefined or incorrectly parsed in your application. This is likely due to the lack of middlewares to handle the body. The curl command sends data as application/x-www-form-urlencoded by default, which Express does not process unless the appropriate middleware is used.

    Additionally, the data argument for fs.writeFile must be a string, buffer, or similar data type, but req.body is currently an object, leading to the TypeError.

    Modify your code like so;

    const express = require('express');
    const fs = require('fs');
    const app = express();
    
    // Middleware to parse URL-encoded data
    app.use(express.urlencoded({ extended: true }));
    
    // Middleware to parse JSON data (optional if your data is JSON)
    app.use(express.json());
    
    app.put('/config/', (req, res) => {
      const filename = '/home/dave/test.txt';
      const data = req.body.data; // Use req.body.data if data is sent as a key-value pair
      if (typeof data !== 'string') {
        res.status(400).send('Invalid data format');
        return;
      }
      fs.writeFile(filename, data, (err) => {
        if (err) {
          console.error(err);
          res.status(500).send('Error writing file');
        } else {
          res.send('Data saved successfully');
        }
      });
    });
    
    app.listen(8008, () => {
      console.log('Server is running on port 8008');
    });
    
    

    Hope this helps.