web-dev-qa-db-ja.com

Reactjsを使用したAxios投稿フォーム

だから私はAxiosでこの投稿メソッドを持っています、そしてこれを提出すると、それは言った

キャッチされていない(約束された)エラー:XMLHttpRequest.handleError(xhr.js:87)でのcreateError(createError.js:16)でのネットワークエラー

この方法を使用する場合:

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

できます。しかし、axios投稿に2つ以上の引数を追加すると、再びエラーが発生します。

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));
  });
});
4
Eko Andri

各状態の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>
    );
  }
}

フォームの送信について、あなたのaxiosの投稿は次のように機能します

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....
      });
  }
6
Afaq Ahmed Khan

axios.post(url[, data[, config]])の3番目の引数は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,
})
3
AKX

どうやら私は各状態のイベントハンドラを追加する必要があります。これをもっとうまく行う方法はありますか?

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>
    )
  }
}
1
Eko Andri