Аксиос Почтовая форма с Reactjs - PullRequest
0 голосов
/ 31 мая 2018

Итак, у меня есть этот метод записи с Axios, и если я отправляю его, он говорит:

Uncaught (в обещании) Ошибка: ошибка сети при createError (createError.js: 16) в XMLHttpRequest.handleError(xhr.js: 87)

Если я использую этот метод:

axios.post('http://localhost:5000/users', ({userid: this.state.userid})

, он работает.Но если я добавлю 2 или более аргумента arg к сообщению axios, он снова получит ошибку:

axios.post('http://localhost:5000/users', ({userid: this.state.userid}, {fullname: this.state.fullname} ))

Вот мой полный код.Как вы можете видеть, я пробую разные комбинации кода, и это работает, только если я передаю только 1 аргумент.

import React from 'react';
import axios from 'axios';
// import { Form } from 'antd';
// import { List, Card, Form } from 'antd';

export default class FormUser extends React.Component {
    // constructor(props) {
    //   super(props)
    //   this.state = {
      state = {
        userid: '',
        fullname: '',
        usergroup:'',
        emailid: '',
        mobile: '',
        title: '',

  };

  handleChange = event => {
    this.setState({ userid: event.target.value });
    this.setState({ fullname: event.target.value });
    this.setState({ usergroup: event.target.value });
    this.setState({ emailid: event.target.value });
    this.setState({ mobile: event.target.value });
    this.setState({ title: event.target.value });
  }

  handleSubmit = event => {
    event.preventDefault();

    // const userform = {userid: this.state.userid};
    // const fullnameForm = {fullname: this.state.fullname};
    // const usergroupForm = {usergroup: this.state.usergroup};
    // const emailidForm = {emailid: this.state.emailid};
    // const mobileForm = {mobile: this.state.mobile};
    // const titleForm = {title: this.state.title};

    axios.post('http://localhost:5000/users', ({userid: this.state.userid}, {fullname: this.state.fullname} )) 
    // { {userid: this.state.userid}, {fullname: this.state.fullname} , usergroup: this.state.usergroup, emailid: this.state.emailid, mobile: this.state.mobile, title: this.state.title }) 
    // { userform, fullnameForm, usergroupForm, emailidForm, mobileForm, titleForm }) 
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>User Project ID:  <input type="text" name="userid" onChange={this.handleChange}/></label><br/>
        <label>Full Name:  <input type="text" name="fullname" onChange={this.handleChange}/></label><br/>
        <label>User Group:  <input type="text" name="usergroup" onChange={this.handleChange}/></label><br/>
        <label>Email:  <input type="text" name="emailid" onChange={this.handleChange}/></label><br/>
        <label>Mobile:  <input type="text" name="mobile" onChange={this.handleChange}/></label><br/>
        <label>Title:  <input type="text" name="title" onChange={this.handleChange}/></label>
        <button type="submit">Add</button>
      </form>
    )
  }
}

AXIOS POST в Express

app.post('/users', function (req, res) {
  var postData = req.body;
  // postData.created_at = new Date();
  connection.query("INSERT INTO users SET ?", postData, function (error, results, fields) {
    if (error) throw error;
    console.log(results.insertId);
    res.end(JSON.stringify(results));
  });
});

Ответы [ 3 ]

0 голосов
/ 31 мая 2018

Так что, очевидно, я должен добавить обработчик событий для каждого состояния.Есть ли способ, которым я могу сделать это лучше?

import React from 'react';
import axios from 'axios';
import { Form } from 'antd';
// import { List, Card, Form } from 'antd';

const FormItem = Form.Item;

export default class FormUser extends React.Component {
  // constructor(props) {
  //   super(props)
  //   this.state = {
  state = {
    userid: '',
    fullname: '',
    usergroup: '',
    emailid: '',
    mobile: '',
    title: '',

  };

  handleUserIDChange = event => {this.setState({ userid: event.target.value })}
  handleFullNameChange = event => {this.setState({ fullname: event.target.value })}
  handleUserGroupChange = event => {this.setState({ usergroup: event.target.value })}
  handleEmailIDChange = event => {this.setState({ emailid: event.target.value })}
  handleMobileChange = event => {this.setState({ mobile: event.target.value })}
  handleTitleChange = event => {this.setState({ title: event.target.value })}

  handleSubmit = event => {
    event.preventDefault();

    // const userform = {userid: this.state.userid};
    // const fullnameForm = {fullname: this.state.fullname};
    // const usergroupForm = {usergroup: this.state.usergroup};
    // const emailidForm = {emailid: this.state.emailid};
    // const mobileForm = {mobile: this.state.mobile};
    // const titleForm = {title: this.state.title};

    axios.post('http://localhost:5000/users',
      { userid: this.state.userid, fullname: this.state.fullname, usergroup: this.state.usergroup, emailid: this.state.emailid, mobile: this.state.mobile, title: this.state.title },)
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (

      // const formItemLayout = {
      //   labelCol: {
      //     xs: { span: 24 },
      //     sm: { span: 8 },
      //   },
      //   wrapperCol: {
      //     xs: { span: 24 },
      //     sm: { span: 16},
      //   },
      // };

      <Form onSubmit={this.handleSubmit}>
        <FormItem>
          <label>User Project ID:  <input type="text" name="this.state.userid" onChange={this.handleUserIDChange} /></label>
        </FormItem>
        <FormItem>
          <label>Full Name:  <input type="text" name="this.state.fullname" onChange={this.handleFullNameChange} /></label><br />
        </FormItem>
        <FormItem>
          <label>User Group:  <input type="text" name="this.state.usergroup" onChange={this.handleUserGroupChange} /></label><br />
        </FormItem>
        <FormItem>
          <label>Email:  <input type="text" name="this.state.emailid" onChange={this.handleEmailIDChange} /></label>
        </FormItem>
        <FormItem>
          <label>Mobile:  <input type="text" name="this.state.mobile" onChange={this.handleMobileChange} /></label>
        </FormItem>
        <FormItem>
          <label>Title:  <input type="text" name="this.state.title" onChange={this.handleTitleChange} /></label>
        </FormItem>
        <button type="submit">Add</button>
      </Form>
    )
  }
}
0 голосов
/ 24 марта 2019

eventHandler для каждого состояния.Есть ли способ, которым я могу сделать это лучше?да, это будет работать примерно так

import React, { Component } from 'react';

class UserForm extends Component {
  constructor() {
    super();
    this.state = {
      fname: '',
      lname: '',
      email: '',
    };
  }

  onChange = (e) => {
    /*
      Because we named the inputs to match their
      corresponding values in state, it's
      super easy to update the state
    */
    this.setState({ [e.target.name]: e.target.value });
  }

  render() {
    const { fname, lname, email } = this.state;
    return (
      <form>
        <input
          type="text"
          name="fname"
          value={fname}
          onChange={this.onChange}
        />
        <input
          type="text"
          name="lname"
          value={lname}
          onChange={this.onChange}
        />
        <input
          type="text"
          name="email"
          value={email}
          onChange={this.onChange}
        />
      </form>
    );
  }
}

, а при отправке формы ваш пост будет работать примерно так

onSubmit = (e) => {
    e.preventDefault();
    // get our form data out of state
    const { fname, lname, email } = this.state;

    axios.post('/', { fname, lname, email })
      .then((result) => {
        //access the results here....
      });
  }
0 голосов
/ 31 мая 2018
Третий аргумент

axios.post(url[, data[, config]]) - это объект конфигурации Axios, который вы непреднамеренно передаете в

axios.post('http://localhost:5000/users', ({userid: this.state.userid}, {fullname: this.state.fullname} ))

, поэтому запрос неправильно настроен и не работает.

Вместо этого все данные для POST должны быть в одном объекте data.

axios.post('http://localhost:5000/users', {
  userid: this.state.userid,
  fullname: this.state.fullname,
})
...