Carlos German
Carlos German

Reputation: 13

react is posting data to console, but data is not successfully making it mysql database

i'm having an issue where my form data is posting to the chrome console, but the payload is not making it's way to the sql database when the query is fired. is it how i've set up axios in the form that is preventing the payload from firing? or is it in my app.post request in the backend?

console error

react form using axios

import React, { Component } from 'react'
import axios from 'axios';

export default class AddVisitorForm extends Component {

  constructor(props) {
    super(props)

    this.state = {
       lastName: '',
       firstName: ''
    }
  }


  onChange = (e) => {
    this.setState({ 
      [e.target.name]: e.target.value
     })
  };

  handleSubmit = (e) => {
    event.preventDefault();
    console.log(this.state)

    const body = this.setState
    axios({
    method: 'post',
    url: 'http://localhost:8000/addactor',
    data: body
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});
  }


  render() {
    const { lastName, firstName } = this.state
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
            <input defaultValue='last name' type="text" name="lastName" onChange={this.onChange } value={lastName} />
            <input defaultValue='first name' type="text" name="firstName" onChange={this.onChange } value={firstName} />
          <button type="submit">Add Guest</button>
        </form>
      </div>
    )
  }
};

express backend

const Actor = require('./models/Actor');
const cors = require('cors');
const bodyParser = require('body-parser')

const app = express();

app.use(cors());
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.use((req, res, next)=>{
  //we say what we want to allow, you can whitelist IPs here or domains
  res.header("Access-Control-Allow-Origin", "*"); 
  //what kind of headers we are allowing
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");  

  //check for the options request from browsers
  //this will always be sent
  if(req.method === "OPTIONS"){
      //tell the browser what he can ask for
      res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
      //we just respond with OK status code
      return res.status(200).json({
          "statusMessage": "ok"
      });
  }

  next();
});



app.post('/addactor', function (req, res) {
  Actor.create({
    lastName: req.body.lastName,
    firstName: req.body.firstName
  })
  .then(function (Actor) {
    res.json(Actor);
  });
});



app.listen(8000);

actor model

const sequelize = require('../database/sequelize');
const Sequelize = require("sequelize");

module.exports = sequelize.define('actor', {
  id: {
    primaryKey: true,
    type: Sequelize.INTEGER,
    field: 'actor_id',
    autoIncrement: true,
    allowNull: false
  },
  lastName: {
    field: 'last_name',
    defaultValue: '',
    type: Sequelize.STRING,
    allowNull: true
  },
  firstName: {
    field: 'first_name',
    defaultValue: '',
    type: Sequelize.STRING,
    allowNull: true
  },
  }, {
  timestamps: false
});

from here, i get a this message in my terminal, and my table rows are left empty besides the auto-incremented ID.

Executing (default): INSERT INTO `actor` (`actor_id`,`last_name`,`first_name`) VALUES (DEFAULT,?,?);

empty rows

Upvotes: 1

Views: 636

Answers (1)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38817

The issue is in your handleSubmit(). Specifically in the setup of the data/body for the axios POST request. You are setting the value of body to that of the function this.setState, instead of just the component's this.state:

handleSubmit = e => {
  event.preventDefault();
  console.log(this.state);
  const body = this.state;
  axios({
    method: "post",
    url: "http://localhost:8000/addactor",
    data: body
  })
    .then(function(response) {
      console.log(response);
    })
    .catch(function(error) {
      console.log(error);
    });
};

Basically change const body = this.setState to const body = this.state.

Upvotes: 1

Related Questions