Skip to content
Advertisement

Can’t Post JSON with Javascript ‘fetch’ in React Native?

I’m currently working on a really simple project. When I tried to console log req.body it gives me empty object.

app.js (React Native)

const musicPlayingHandle = () => {
    setMusicPlaying(!isMusicPlaying);
    fetch('http://192.168.1.23:3000/musicHandler', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type' : 'application/json'
      },
      body: JSON.stringify(data)
    })
    .then((response) => response.json())
    .then((res) => {
      return res;
    })
  }

server.js (Node JS Backend API)

require('dotenv').config();

const express = require('express');
const ejs = require('ejs');
const cors = require('cors');

const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.set('view engine', 'ejs');                          
app.set('views', __dirname+'/views');                   
app.use(express.static('public'));

app.get('/', (req, res) => {
    res.render('index');
});

app.post('/musicHandler', (req, res) => {
    console.log(req.body);
    res.json({'msg': 'OK!'});
});

app.listen(3000, '0.0.0.0', () => {
    console.log('Canım Çok Sıkıldı Çalışıyor...');
});

Advertisement

Answer

You should parse the incoming requests with JSON payloads.

In server.js add the middleware fucntion:

app.use(express.json())
Advertisement