0

I'm creating my own API (with express) and react.js application. However, when I send the data from the react app, it is not retrieved by the server. Here's my code:

POST Request Client Side:

async function sendRequest(text) {

    const url = "http://localhost:51515/initialize"
    const settings = {
        method: "POST",
        body: {
            text: text
        }
    }
        
    try {
        const response = await fetch(url, settings)
        return await response.json()
    } catch(err) {
        console.log(err)
    }
}

Server Side POST Request Retrieval:

const express = require("express");
const app = express();
const PORT = 51515

app.use(express.json())

app.listen(
    PORT,
    () => console.log(`API initialized on http://localhost:${PORT}`)
)

app.post('/initialize', (req,res) => {
    console.log(req.body) // The log output is {}
})

Do you know how I can fix this?

Rahul Kumar
  • 3,009
  • 2
  • 16
  • 22
Efe FRK
  • 177
  • 1
  • 13
  • perhaps you aren't sending JSON - try `express.text()` body parser instead - or, of course, send JSON – Bravo Aug 06 '21 at 04:41
  • 1
    oh, I see ... you need `body: JSON.stringify({ text: text })` (or just `body: JSON.stringify({ text })` if you want) – Bravo Aug 06 '21 at 04:49
  • Well still there's no value, it didn't change anything. – Efe FRK Aug 06 '21 at 05:10
  • you didn't tell the server you're sending JSON ... `headers: { "Content-Type": "application/json" }` - it's in the answer below – Bravo Aug 06 '21 at 05:12

1 Answers1

1

You just need to add these parameters to your settings object.

const settings = {
    method: "POST",
    body: JSON.stringify({
        text: text
    }),
    headers: { "Content-Type": "application/json" }
}
ErcouldnT
  • 39
  • 6
  • Did it but now it gives this error: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. – Efe FRK Aug 06 '21 at 05:05
  • 1
    Efe, your Express api and React app are not serving in same server. You can easily solve this problem using Cors. Just "npm install cors" to your backend server then "const cors = require('cors')" and "app.use(cors())" it. – ErcouldnT Aug 06 '21 at 05:09
  • Nothing much :) – ErcouldnT Aug 06 '21 at 05:16