0
votes

I'm currently trying to post form data (axios) from a react frontend to my express app to the mysql database using sequelize. Thus far, I can successfully make a GET request and display to the UI. when setting up my post request, though, i'm getting a 404 error in the console. I've done quite a bit of reading, granted i'm very new and some ideas may just be going right over my head, but I can't seem to crack the case as to why i can successfully make a GET request, but not a post request, even to the console. I'm also curious as to best practice for setting up a POST endpoint.

here's my code so far:

client form

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)
    axios.post('http://localhost:8000/', this.state)
    .then(response => {
      console.log(response)
    })
    .catch(error => {
      console.log(error)
    })
  }


  render() {
    const { lastName, firstName } = this.state
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Last Name:
            <input type="text" name="lastName" onChange={this.onChange } value={lastName} />
          </label>
          <label>
            First Name:
            <input type="text" name="firstName" onChange={this.onChange } value={firstName} />
          </label>
          <button type="submit">Add Guest</button>
        </form>
      </div>
    )
  }
};

sequelize model

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

module.exports = sequelize.define('actor', {
  lastName: {
    field: 'last_name',
    type: Sequelize.STRING
  },
  firstName: {
    field: 'first_name',
    type: Sequelize.STRING
  },
  }, {
  timestamps: false
});

express app

const express = require("express");
const Actor = require('./models/Actor');
const cors = require('cors');

const app = express();

app.use(cors());


app.get('/actor', function(request, response) {
  Actor.findAll().then((actor) => {
    response.json(actor);
  });
});

app.get('/actor/:id', function(request, response) {
  let id = request.params.id;

  Actor.findByPk(id).then((actor) => {
    if (actor) {
      response.json(actor);
    } else {
      response.status(404).send();
    }
  });
});

app.post('/addactor', function(request, response) {
  Actor.create()
}



app.listen(8000);

you'll notice the app.post function is incomplete, as i'm not too sure how to set this up with form data. i know it's not the hardest thing in the world to figure out, but i just can't seem to get the post request to display in the console, nor how to properly set up the post request in the express app to insert data into the mysql table. if anybody could shed some light to help me get back on track, i'd appreciate it so much.

1

1 Answers

0
votes

You should response to POST. Below is right code. response.json write response to request. If you don't explicitly write response, express server hang on do nothing.

app.post('/addactor', function(request, response) {
  Actor.create().then(createdInstance => {
     response.json(createdInstance)
  })
}

If you don't want to response in this function, write like this.

app.post('/addactor', function(request, response, next) {
  Actor.create()
  next()
}

next function move to next matching route.

If you just want to response OK if success, and 404 if fail, write

app.post('/addactor', function(request, response, next) {
  Actor.create().then(() => {
     response.end()
  }).catch(error => {
     response.status(404).end()
  })
}

next function move to next mating route.

request body, and request params are accessible like this

app.post('/addactor', function(request, response, next) {
  const body = request.body // json body parsed to javascript object {lastName: '', firstName: ''}
  const params = request.params // query parameters parsed to javascript object
  Actor.create(body).then(() => {
     response.end()
  }).catch(error => {
     response.status(404).end()
  })
}

This code is insecure, so you should write some filters and validations.

Express Doc