最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

反应是将数据发布到控制台,但是数据无法成功将其添加到mysql数据库中

网站源码admin23浏览0评论

反应是将数据发布到控制台,但是数据无法成功将其添加到mysql数据库中

反应是将数据发布到控制台,但是数据无法成功将其添加到mysql数据库中

我在将表单数据发布到chrome控制台时遇到问题,但是在触发查询时,有效负载无法将其传递到sql数据库。我是如何以防止有效载荷触发的形式设置axios的?还是在后端的app.post请求中?

console error

使用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);

演员模型

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
});

从这里,我在终端中收到此消息,除了自动递增的ID,我的表行都留空。

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

empty rows

回答如下:

问题出在您的handleSubmit()中。特别是在为axios POST请求设置data / body时。您正在将body的值设置为功能setState的值,而不仅仅是组件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);
    });
};

基本上将const body = this.setState更改为const body = this.state

希望有帮助!

发布评论

评论列表(0)

  1. 暂无评论