Home > OS >  unable to get values for react js in node
unable to get values for react js in node

Time:05-06

I want to send values from react to node. I am using fetch but I am not getting. Here's the code: React Code:

    const values = {email,pass}
    
    const data = {
        method: 'POST',
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(values),
    }
    
    fetch('http://localhost:8000/', data)
    .then(res => res.json())
    .then(data => console.log(data))

Node Code:

const express = require("express")

const cors = require('cors')

const app = express()

app.use( cors({ origin: '*' }) )

app.listen(8000, 'localhost')

app.post('/' , ( req, res ) => {

console.log(req.body)

} )

CodePudding user response:

use json body parser:

app.use(express.json());

CodePudding user response:

You need express to use json body parser:

app.use(express.json());

Additionally you are not sending any response from your Node Server to the client, try something like this this:

app.post('/' , ( req, res ) => { 

  console.log(req.body) 

  const data = JSON.stringify(req.body) 

  console.log(data) 

  res.status(200).json({data: data});

})
  • Related