1

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...');
});
3
  • What is data? How sure are you it's not an empty object? How sure are you that it's JSON serializable? Commented Apr 4, 2021 at 17:19
  • @JaredSmith 'const data = { value: isMusicPlaying.toString() };' i saw this on internet also i tried so much other ways and im logging when app get an post request imgur.com/a/L2VFql5 this is the output when i send post request via react native Commented Apr 4, 2021 at 17:21
  • i think you need to put body-parser on the express setting expressjs.com/en/resources/middleware/body-parser.html . Also don't forget to try catch in the backend. and in the frontend after the last then you can add catch like => then((res) => return res).catch((err)=>console.log(err)) Commented Apr 4, 2021 at 18:25

1 Answer 1

2

You should parse the incoming requests with JSON payloads.

In server.js add the middleware fucntion:

app.use(express.json())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.