-1

I'm using a fetch request with the PUT method and giving a body but when I call the endpoint that I defined on my server page, I keep getting undefined.

Does anyone know why?

Here's where the call comes from:

<tr>
  <td><%= index %></td>
  <td class="editable" id="item">
    <%= item %>
  </td>
  <td class="editable" id="desc">
    <%= desc %>
  </td>
  <td class="editable" id="status">
    <%= status %>
  </td>
  <td class="editable" id="priority">
    <%= priority %>
  </td>
  <td><button id="delete-button">Delete</button>
    <button onclick="refetch(this)">Edit</button>
  </td>
</tr>

<script>
  async function refetch(btn) {
    if (btn.innerHTML === 'Edit') {
      await fetch('http://localhost:3000/todo', {
        method: 'PUT',
        body: {
          edit: 'true'
        }
      })
    }
  }
</script>

And my endpoint:

app.put("/todo", (req, res) => {
  console.log(req.body);
});
ether
  • 91
  • 5

1 Answers1

0

Although the question did not mention, I assumed you're using express framework.

The reason for that is most likely that you're not using body-parser to allow posting data to your endpoint.

You can find out more about on this https://stackoverflow.com/questions/38306569/what-does-body-parser-do-with-express#:~:text=No%20need%20to%20install%20body,you%20will%20receive%20post%20request..

Try this: npm install body-parser

Then just before your your app.put(/todo) add this:

app.use(require("body-parser").urlencoded({ extended: false }));

Then try again, I'd recommend you use Postman to test your endpoint accordingly before doing E2E tests.

Here's a working example

On Postman

I hope it helps, good luck!

gugateider
  • 1,983
  • 2
  • 13
  • 17
  • The question has the `express` tag. That should be enough, it doesn't have to say it in the text. – Barmar Mar 31 '23 at 23:27
  • 1
    The problem isn't the body-parser. The problem is that `fetch()` will not automatically convert the object to JSON, you have to call `JSON.stringify()` explicitly in the client. – Barmar Mar 31 '23 at 23:28
  • @Barmar , I did not notice the express tag. Thank you for that. However, it's not JSON.stringify, the problem is the lack of body-parser middleware in express. You can easily test the endpoint I posted above without JSON.stringify and will still work. – gugateider Mar 31 '23 at 23:29
  • The problem was I needed to add this line of code to my index.js. I overlooked it, app.use("/", express.json()); – ether Mar 31 '23 at 23:30
  • @ether I'm glad you've solved it! Cheers!! – gugateider Mar 31 '23 at 23:31
  • 1
    I can't find any mention in the `fetch()` documentation that `body` will be stringified automatically if it's a plain object. Maybe this is browser-specific? – Barmar Mar 31 '23 at 23:36
  • @Barmar It won't. The OPs code is sending `[object Object]` as the body. They did however mention "*Added headers and the JSON.stringify*" in a comment – Bergi Apr 01 '23 at 08:36