Troubleshooting data transfer from React to Node.js server using Fetch API

I’m having trouble sending JSON data from my React app to my Node.js server. I’m using the Fetch API but the server is receiving an empty req.body. I can’t figure out what’s going wrong.

Here’s my React code:

function App() {
  const sendData = () => {
    fetch('http://localhost:3000/api', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({user: 'John'})
    })
  }

  return (
    <div>
      <h1>Data Sender App</h1>
      <button onClick={sendData}>Send Data</button>
    </div>
  )
}

And here’s my server code:

const express = require('express')
const cors = require('cors')
const app = express()

app.use(cors())
app.use(express.json())

app.post('/api', (req, res) => {
  console.log(req.body)
  res.json({message: 'Received'})
})

app.listen(3000, () => console.log('Server running on port 3000'))

I’ve checked the Fetch API docs but can’t find why the data isn’t reaching the server. Any ideas what might be causing this?

hey mate, i had a similar issue before. make sure ur using the right content-type header. also, double-check if ur server is actually parsing JSON correctly. sometimes its the little things that trip us up! maybe try logging the raw request on the server side to see whats coming thru?

I’ve faced this exact problem before, and it can be frustrating. One thing that’s not immediately obvious is that some browsers (looking at you, Safari) can be finicky with CORS preflight requests for POST methods. Try adding ‘Content-Type’ to your CORS allowed headers:

app.use(cors({
  allowedHeaders: ['Content-Type', 'Authorization']
}));

Also, make sure your server is actually waiting for the request body to be fully received before processing it. You might want to add body-parser middleware:

const bodyParser = require('body-parser');
app.use(bodyParser.json());

If none of that works, try using a tool like Postman to test your API endpoint directly. This can help isolate whether the issue is on the client or server side. Good luck!

I encountered a similar issue in one of my projects. Have you verified that the CORS middleware is correctly configured? Sometimes, CORS can interfere with data transmission. Also, ensure your Express app is using the JSON parser middleware before your routes. Try moving the app.use(express.json()) line above the CORS middleware. If that doesn’t work, you might want to check if there are any network errors in your browser’s developer console. Lastly, consider adding error handling to your fetch call to catch and log any potential issues on the client side.