Skip to content Skip to sidebar Skip to footer

Pass Data From React To Node Express Server

I am trying to pass the generalDetail data from my react front end to my node server. I am currently getting a connection refused error. (OPTIONS http://localhost:5000/api/home n

Solution 1:

You can change your code into this

Example

onSubmitForm = e => {
        e.preventDefault();
        let data = {
              generalDetail: this.state.generalDetails,
              firstName: this.state.firstName,
              middleName: this.state.middleName,
              lastName: this.state.lastName
        };

        axios.post("http://localhost:5000/api/home", data).then(() => {
           //do something
         }).catch(() => {
            console.log("Something went wrong. Plase try again later");
        });
    }

Solution 2:

try this

const express = require('express')
const app = express()
const port = 8000//your port numberconst cors = require('cors')
app.use(cors())
var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 

Solution 3:

Try to add cors preflight code in your backend code (server.js).

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  res.header("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS");
  res.header("Access-Control-Allow-Credentials", true);
  next();
});
app.post('/api/home', (req, res) => {
  const data = [{ generalDetails: req.body.generalDetail }];
  res.json(data);
});

Post a Comment for "Pass Data From React To Node Express Server"