首页 > 解决方案 > ReactJS Axios 使用 Multer 传递数据和上传图片

问题描述

美好的一天,我正在 ReactJS 中制作一个注册表单,该注册表单包含名字、姓氏、电子邮件、密码、生日和上传图片的字段。我设法将图像上传到服务器,但是我无法添加其他字段名、姓、电子邮件、密码和生日,它有一个错误Illegal arguments: undefined, string,我可以知道我做错了什么吗?谢谢你。

ReactJS 提交事件

import React, { Component } from "react";
import { Link } from "react-router-dom";

import DatePicker from "react-datepicker";
import moment from "moment";

import axios from "axios";

class Register extends Component {
  constructor(props) {
    super(props);
    this.state = {
      startDate: moment(),
      firstname: "",
      lastname: "",
      email: "",
      password: "",
      dateofbirth: "",
      receipt: "",
      description: ""
    };
    this.handleChange = this.handleChange.bind(this);
    this.onChange = this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this.fileSelectHandler = this.fileSelectHandler.bind(this);
  }

  handleChange(date) {
    this.setState({
      startDate: date
    });
  }

  fileSelectHandler = event => {
    this.setState({
      receipt: event.target.files[0]
    });
  };

  onChange(e, date) {
    switch (e.target.name) {
      case "receipt":
        this.setState({ receipt: e.target.files[0] });
        break;
      default:
        this.setState({ [e.target.name]: e.target.value });
    }
    e.preventDefault();
  }

  onSubmit(e) {
    e.preventDefault();
    const { description, receipt } = this.state;
    const bodyFormData = new FormData();

    bodyFormData.append("receipt", receipt);

    bodyFormData.append("description", description);

    bodyFormData.append("firstname", this.state.firstname);
    bodyFormData.append("lastname", this.state.lastname);
    bodyFormData.append("password", this.state.password);
    bodyFormData.append("email", this.state.email);

    const newUser = {
      firstname: this.state.firstname,
      lastname: this.state.lastname,
      email: this.state.email,
      password: this.state.password,
      dateofbirth: document.getElementById("date").value
    };

    axios
      .post("/api/users/register", bodyFormData, newUser, {
        headers: {
          accept: "application/json",
          "Accept-Language": "en-US,en;q=0.8"
        }
      })
      .then(function(res) {
        console.log(res.data);
      })
      .catch(err => console.log(err));

    console.log(bodyFormData);
  }

  render() {
    return (
      <div className="container_child signup_container">
        <div className="signup_thumbnail">
          <div className="thumbnail__content">
            <h1 className="heading-primary">this is overlay with image</h1>
            <h2 className="heading-secondary">
              this is overlay with imagessss
            </h2>
          </div>
          <div className="signup__overlay" />
        </div>
        <div className="container_child signup_form">
          <form onSubmit={this.onSubmit} encType="multipart/form-data">
            <div className="form-group">
              <label htmlFor="username">Firstname</label>
              <input
                className="form-control"
                type="text"
                name="firstname"
                id="firstname"
                placeholder="Juan"
                value={this.state.firstname}
                onChange={this.onChange}
              />
            </div>
            <div className="form-group">
              <label htmlFor="lastname">Last Name</label>
              <input
                className="form-control"
                type="text"
                name="lastname"
                id="last-name"
                placeholder="Dela Cruz"
                value={this.state.lastname}
                onChange={this.onChange}
              />
            </div>
            <div className="form-group">
              <label htmlFor="prcid">Email</label>
              <input
                className="form-control"
                type="email"
                name="email"
                id="email"
                placeholder="juan@gmail.com"
                value={this.state.email}
                onChange={this.onChange}
              />
            </div>
            <div className="form-group">
              <label htmlFor="prcid">Password</label>
              <input
                className="form-control"
                type="password"
                name="password"
                id="password"
                value={this.state.password}
                onChange={this.onChange}
              />
            </div>

            <div className="form-group">
              <label htmlFor="prcid">Birthday:</label>
              <DatePicker
                id="date"
                selected={this.state.startDate}
                onChange={this.handleChange}
              />;
            </div>

            <div className="form-group">
              <div
                className="mdl-textfield mdl-js-textfield mdl-textfield--file is-upgraded"
                data-upgraded=",MaterialTextfield"
              >
                <input
                  className="mdl-textfield__input"
                  placeholder="File"
                  type="text"
                  id="uploadFile"
                  name="description"
                  value={this.state.description}
                  onChange={this.onChange}
                  //readonly="true"
                />
                <div className="">
                  <input
                    type="file"
                    ref="files"
                    id="uploadBtn"
                    name="receipt"
                    onChange={this.onChange}
                  />
                </div>
                {/* // <Dropzone onDrop={this.onDrop}>
                  //   <div>Try dropping some files here, or click to select files to upload.</div>
                  // </Dropzone> */}
              </div>
            </div>
            <div className="m-t-lg">
              <ul className="list-inline">
                <li>
                  <input
                    className="btn btn--form"
                    type="submit"
                    value="Register"
                  />
                </li>
                <li>
                  <Link to="/login">I am already a member</Link>
                </li>
              </ul>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

export default Register;

标签: javascriptreactjs

解决方案


您正在使用 document.getElementById 来获取日期的值,为什么不尝试使用 this.state.startDate 由于 react DOM 是虚拟的而不是真实的 DOM,您将通过 document.getElementById 获得的值会为空

const newUser = {
  firstname: this.state.firstname,
  lastname: this.state.lastname,
  email: this.state.email,
  password: this.state.password,
  dateofbirth: this.state.startDate
};

推荐阅读