Failed prop type: Invalid prop `errors` of type `string` supplied to `CreateProfile`, expected `object`

时间:2019-01-07 14:06:51

标签: node.js reactjs express redux mern

I am trying to create a profile for a user on login, after submitting the form I am getting the error as invalid props errors. As both my client and server are running.I am using redux in my react app. Below is my code. I am building a MERN stack application. I am trying to create a profile for a user on login, after submitting the form I am getting the error as invalid props errors. As both my client and server are running.I am using redux in my react app. Below is my code. I am building a MERN stack application.

 import React, { Component } from "react";
    import { connect } from "react-redux";
    import { withRouter } from "react-router-dom";
    import PropTypes from "prop-types";
    import TextFieldGroup from "../common/TextFieldGroup";
    import TextAreaFieldGroup from "../common/TextAreaFieldGroup";
    import SelectListGroup from "../common/SelectListGroup";
    import InputGroup from "../common/InputGroup";
    import { createProfile } from "../../actions/profileActions";

    class CreateProfile extends Component {
      constructor(props) {
        super(props);
        this.state = {
          displaySocialInputs: false,
          handle: "",
          company: "",
          website: "",
          location: "",
          status: "",
          skills: "",
          githubusername: "",
          bio: "",
          twitter: "",
          facebook: "",
          linkedin: "",
          youtube: "",
          instagram: "",
          errors: {}
        };
        this.onChange = this.onChange.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
      }

      componentWillReceiveProps(nextProps) {
        if (nextProps.errors) {
          this.setState({ errors: nextProps.errors });
        }
      }

      onSubmit(e) {
        e.preventDefault();

        const profileData = {
          handle: this.state.handle,
          company: this.state.company,
          website: this.state.website,
          location: this.state.location,
          status: this.state.status,
          skills: this.state.skills,
          githubusername: this.state.githubusername,
          bio: this.state.bio,
          twitter: this.state.twitter,
          facebook: this.state.facebook,
          linkedin: this.state.linkedin,
          youtube: this.state.youtube,
          instagram: this.state.instagram
        };
        this.props.createProfile(profileData, this.props.history);
      }

      onChange(e) {
        this.setState({ [e.target.name]: e.target.value });
      }

      render() {
        const { errors, displaySocialInputs } = this.state;

        let socialInputs;

        if (displaySocialInputs) {
          socialInputs = (
            <div>
              <InputGroup
                placeholder="Twitter Profile URL"
                name="twitter"
                icon="fab fa-twitter"
                value={this.state.twitter}
                onChange={this.onChange}
                error={errors.twitter}
              />

              <InputGroup
                placeholder="Facebook Page URL"
                name="facebook"
                icon="fab fa-facebook"
                value={this.state.facebook}
                onChange={this.onChange}
                error={errors.facebook}
              />

              <InputGroup
                placeholder="Linkedin Profile URL"
                name="linkedin"
                icon="fab fa-linkedin"
                value={this.state.linkedin}
                onChange={this.onChange}
                error={errors.linkedin}
              />

              <InputGroup
                placeholder="YouTube Channel URL"
                name="youtube"
                icon="fab fa-youtube"
                value={this.state.youtube}
                onChange={this.onChange}
                error={errors.youtube}
              />

              <InputGroup
                placeholder="Instagram Page URL"
                name="instagram"
                icon="fab fa-instagram"
                value={this.state.instagram}
                onChange={this.onChange}
                error={errors.instagram}
              />
            </div>
          );
        }

        //select options for status
        const options = [
          { label: "* Select Professional Status", value: 0 },
          { label: "Developer", value: "Developer" },
          { label: "Junior Developer", value: "Junior Developer" },
          { label: "Senior Developer", value: "Senior Developer" },
          { label: "Manager", value: "Manager" },
          { label: "Student or Learning", value: "Student or Learning" },
          { label: "Instructor or Teacher", value: "Instructor or Teacher" },
          { label: "Intern", value: "Intern" },
          { label: "Other", value: "Other" }
        ];

        return (
          <div className="create-profile">
            <div className="container">
              <div className="row">
                <div className="col-md-8 m-auto">
                  <h1 className="display-4 text-center">Create Your Profile</h1>
                  <p className="lead text-center">
                    Let's get some information to make your profile stand out
                  </p>
                  <small className="d-block pb-3">* = required fields</small>
                  <form onSubmit={this.onSubmit}>
                    <TextFieldGroup
                      placeholder="* Profile Handle"
                      name="handle"
                      value={this.state.handle}
                      onChange={this.onChange}
                      error={errors.handle}
                      info="A unique handle for your profile URL. Your full name, company name, nickname"
                    />
                    <SelectListGroup
                      placeholder="Status"
                      name="status"
                      value={this.state.status}
                      onChange={this.onChange}
                      options={options}
                      error={errors.status}
                      info="Give us an idea of where you are at in your career"
                    />
                    <TextFieldGroup
                      placeholder="Company"
                      name="company"
                      value={this.state.company}
                      onChange={this.onChange}
                      error={errors.company}
                      info="Could be your own company or one you work for"
                    />
                    <TextFieldGroup
                      placeholder="Website"
                      name="website"
                      value={this.state.website}
                      onChange={this.onChange}
                      error={errors.website}
                      info="Could be your own website or a company one"
                    />
                    <TextFieldGroup
                      placeholder="Location"
                      name="location"
                      value={this.state.location}
                      onChange={this.onChange}
                      error={errors.location}
                      info="City or city & state suggested (eg. Boston, MA)"
                    />
                    <TextFieldGroup
                      placeholder="* Skills"
                      name="skills"
                      value={this.state.skills}
                      onChange={this.onChange}
                      error={errors.skills}
                      info="Please use comma separated values (eg.
                        HTML,CSS,JavaScript,PHP"
                    />
                    <TextFieldGroup
                      placeholder="Github Username"
                      name="githubusername"
                      value={this.state.githubusername}
                      onChange={this.onChange}
                      error={errors.githubusername}
                      info="If you want your latest repos and a Github link, include your username"
                    />
                    <TextAreaFieldGroup
                      placeholder="Short Bio"
                      name="bio"
                      value={this.state.bio}
                      onChange={this.onChange}
                      error={errors.bio}
                      info="Tell us a little about yourself"
                    />
                    <div className="mb-3">
                      <button
                        type="button"
                        onClick={() => {
                          this.setState(prevState => ({
                            displaySocialInputs: !prevState.displaySocialInputs
                          }));
                        }}
                        className="btn btn-light"
                      >
                        Add Social Network Links
                      </button>
                      <span className="text-muted">Optional</span>
                    </div>
                    {socialInputs}
                    <input
                      type="submit"
                      value="Submit"
                      className="btn btn-info btn-block mt-4"
                    />
                  </form>
                </div>
              </div>
            </div>
          </div>
        );
      }
    }

    CreateProfile.propTypes = {
      profile: PropTypes.object.isRequired,
      errors: PropTypes.object.isRequired
    };
    const mapStateToProps = state => ({
      profile: state.profile,
      errors: state.errors
    });
    export default connect(
      mapStateToProps,
      { createProfile }
    )(withRouter(CreateProfile));

export const createProfile = (profileData, history) => dispatch => {
  axios
    .post("http://localhost:8080/api/profile", profileData)
    .then(res => history.push("/"))
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      })
    );
};
------------------------------------------------------------------
server side route :-

//post - api/profile   **private
//create or edit user profile
router.post(
  "/",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const { errors, isValid } = validateProfileInput(req.body);

    // Check Validation
    if (!isValid) {
      // Return any errors with 400 status
      return res.status(400).json(errors);
    }

    // Get fields
    const profileFields = {};
    profileFields.user = req.user.id;
    if (req.body.handle) profileFields.handle = req.body.handle;
    if (req.body.company) profileFields.company = req.body.company;
    if (req.body.website) profileFields.website = req.body.website;
    if (req.body.location) profileFields.location = req.body.location;
    if (req.body.bio) profileFields.bio = req.body.bio;
    if (req.body.status) profileFields.status = req.body.status;
    if (req.body.githubusername)
      profileFields.githubusername = req.body.githubusername;
    // Skills - Spilt into array
    if (typeof req.body.skills !== "undefined") {
      profileFields.skills = req.body.skills.split(",");
    }

    // Social
    profileFields.social = {};
    if (req.body.youtube) profileFields.social.youtube = req.body.youtube;
    if (req.body.twitter) profileFields.social.twitter = req.body.twitter;
    if (req.body.facebook) profileFields.social.facebook = req.body.facebook;
    if (req.body.linkedin) profileFields.social.linkedin = req.body.linkedin;
    if (req.body.instagram) profileFields.social.instagram = req.body.instagram;

    Profile.findOne({ user: req.user.id }).then(profile => {
      if (profile) {
        // Update
        Profile.findOneAndUpdate(
          { user: req.user.id },
          { $set: profileFields },
          { new: true }
        ).then(profile => res.json(profile));
      } else {
        // Create

        // Check if handle exists
        Profile.findOne({ handle: profileFields.handle }).then(profile => {
          if (profile) {
            errors.handle = "That handle already exists";
            res.status(400).json(errors);
          }

          // Save Profile
          new Profile(profileFields).save().then(profile => res.json(profile));
        });
      }
    });
  }
);

1 个答案:

答案 0 :(得分:0)

您是否检查了发布路线?我遇到了同样的问题,并通过正确地写出路线解决了该问题

尝试

router.post(
  "/api/profile"

代替

router.post(
  "/"

不确定,但是我在输入时遇到错字,解决了完全相同的问题