0

I am sending a simple fetch() to my server as follows:

eo.put = function (state) {
  
  console.log('PUT:state', state);

  let _id = encodeURIComponent(state._id);
  const options = { 
    headers: {'Content-Type': 'application/json'}, 
    method: 'PUT', 
    body: JSON.stringify(state)
  };
  fetch("/articles/put/" + _id, options )
    .then((response) => {
      console.log('RESPONSE', response);
      // you need to update the DOM here
    })
    .catch((error) => {
      console.error("DEBUG: fetch/PUT error", error);
    });
}

and I can verify that state is populated with the console.log().

However; on the server side req.body is not populated and shows undefined.

// .. snip
app.use('/articles', routes.articles);
// .. snip

// UPDATE OPERATIONS
router.route('/put/:_id').put((req, res) => {
  const _id = req.params._id;
  const obj = req.body;
  

      /*
      **
      ** req.body is empty
      **
      */
      debug && console.log('DEBUG: route: /articles/put : req.body', req.body);
    
      DBM.updateArticle(_id, obj).then(() => {
      }).catch((err)=>{
        res.status(500).send("DEBUG: database internal error", err);
      });
      res.end();
    });
  • the URLs don't seem to match. – Daniel A. White Oct 25 '21 at 22:57
  • also you need the JSON express plugin. – Daniel A. White Oct 25 '21 at 22:57
  • The URLs match ... I have verified the route is being hit on the server ... you just can't see the `/articles` in the code I have up there. What do you mean by JSON express plugin? –  Oct 25 '21 at 23:00
  • I added in the app.use command above ... Express can handle JSON without a plugin I believe. –  Oct 25 '21 at 23:03
  • app.use(express.json()); ... I had commented this command out and that was breaking the body ... it is called built in middleware ... thanks for pointing me in the right direction ... –  Oct 25 '21 at 23:24

1 Answers1

1

Most likely you need to add a body-parser

const bodyParser = require('body-parser')

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

// your routes...
demark-pro
  • 174
  • 5
  • It's pretty odd but they have gone back and forth on to wether or not you need to install it separately ... I do not as I am using the latest version of Express ... see here ... https://stackoverflow.com/questions/47232187/express-json-vs-bodyparser-json/47232318 –  Oct 27 '21 at 02:23
  • @jonjonbonbon Thanks, I didn't know. In the end , what was your problem ? – demark-pro Oct 27 '21 at 02:31
  • I had forgot to include `app.use(express.json)` ... very odd statement ... probably why I forgot ... if it can parse JSON ... just parse it ... but you have to tell it to. –  Oct 27 '21 at 02:32