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.