0

I have a problem with my form submit. I am getting :ERR_EMPTY_RESPONSE after submit. I want to send a form with photo. All looks good from postman. My POST is working, but when i want to use my form I am having an issue This is my front end part

import React, { Component } from 'react';
import axios from 'axios';

import Button from '../../common/Buttons/Button';

import { API_URL } from '../../../config';
import { isAuthUser } from '../../../utils/utils';

class ProjectCreate extends Component {
  state = {
    formData: {
      creator: '',
      title: '',
      description: '',
      shortDescription: '',
      photo: '',
      tags: '',
      projectType: '',
      git: '',
      demo: '',
    },
    displayLinks: false,
    loading: false,
  };

  createProject = async (formData) => {
    this.setState({ loading: true });
    const { token } = isAuthUser();
    const config = {
      headers: {
        Accept: 'application/json',
        // 'Content-Type': 'application/json',
        Authorization: `${token}`,
      },
    };
    try {
      console.log('axios data', formData);
      await axios
        .post(
          `${API_URL}/projects/create/${this.props.match.params.userId}`,
          formData,
          config
        )
        .then((res) => res.data);
      this.setState({ loading: false });
    } catch (err) {}
  };

  onChange = (e) => {
    // setting formData in the state properly
    const { formData } = this.state;
    let newFormData = { ...formData };
    newFormData[e.target.name] = e.target.value;
    this.setState({
      formData: newFormData,
    });
  };
  onSubmit = (e) => {
    const { formData } = this.state;

    e.preventDefault();
    this.createProject(formData);
  };

  toggleLinks = () => {
    const { displayLinks } = this.state;
    if (!displayLinks) {
      this.setState({ displayLinks: true });
    } else {
      this.setState({ displayLinks: false });
    }
  };

  render() {
    const {
      displayLinks,
      formData: {
        title,
        description,
        shortDescription,
        photo,
        tags,
        projectType,
        git,
        demo,
      },
    } = this.state;

    return (
      <section className=''>
        <h1 className=''>Create Project</h1>
        <p className=''>
          <i className='fas fa-user'></i> Add project information
        </p>
        <small>* = required field</small>
        <form
          encType='multipart/form-data'
          className='form'
          onSubmit={(e) => this.onSubmit(e)}>
          <div className=''>
            <select
              name='projectType'
              value={projectType}
              onChange={this.onChange}>
              <option value='0'>* Select Project Type Status</option>
              <option value='Front-end'>Front-end</option>
              <option value='Back-end'>Back-end</option>
              <option value='MERN'>MERN</option>
              <option value='Vanila JS'>Vanila JS</option>
              <option value='html'>HTML/CSS</option>
            </select>
            <small className='form-text'>Select a project type.</small>
          </div>
          <div className='form-group'>
            <input
              type='text'
              placeholder='Title'
              name='title'
              value={title}
              onChange={this.onChange}
            />
            <small className='form-text'>Add project title.</small>
          </div>
          <div className='form-group'>
            <input
              type='text'
              placeholder='Description'
              name='description'
              value={description}
              onChange={this.onChange}
            />
            <small className='form-text'>Add project description</small>
          </div>
          <div className='form-group'>
            <input
              type='text'
              placeholder='Short description'
              name='shortDescription'
              value={shortDescription}
              onChange={this.onChange}
            />
            <small className='form-text'>Add project short description</small>
          </div>
          <div className='form-group'>
            <input
              type='text'
              placeholder='* Tags'
              name='tags'
              value={tags}
              onChange={this.onChange}
            />
            <small className='form-text'>
              Please use comma separated values (eg. HTML,CSS,JavaScript,PHP)
            </small>
          </div>
          <div className='form-group'>
            <input
              type='file'
              accept='.jpg, .png, .jpeg'
              placeholder='Photo'
              name='photo'
              value={photo}
              onChange={this.onChange}
            />
            <small className='form-text'>Add project preview.</small>
          </div>
          <div className='my-2'>
            <button onClick={this.toggleLinks} type='button' className=''>
              Add Project Links
            </button>
            <span>Optional</span>

            {displayLinks && (
              <div>
                <div className=''>
                  <i className=''></i>
                  <input
                    type='text'
                    placeholder='Git URL'
                    name='git'
                    value={git}
                    onChange={this.onChange}
                  />
                </div>

                <div className=''>
                  <i className=''></i>
                  <input
                    type='text'
                    placeholder='Demo URL'
                    name='demo'
                    value={demo}
                    onChange={this.onChange}
                  />
                </div>
              </div>
            )}
          </div>

          <input type='submit' className='btn btn-primary my-1' />
          <Button className='btn btn-light my-1' to='/projects'>
            Go Back
          </Button>
        </form>
      </section>
    );
  }
}

export default ProjectCreate;

My state is change when I type in form and my console.log is returning formData

This is my POST


/* create projects */
exports.create = (req, res) => {
  let form = new formidable.IncomingForm();
  form.keepExtensions = true;
  form.parse(req, (err, fields, files) => {
    if (err) {
      return res
        .status(400)
        .json({ errors: [{ msg: 'Image could not be uploaded' }] });
    }

    const { git, demo } = fields;

    fields.creator = req.user._id;

    fields.links = {};
    if (git) fields.links.git = git;
    if (demo) fields.links.demo = demo;

    let project = new Project(fields);

    //1kb = 1000
    //1mb = 1000000kb
    //name 'photo' mus match client side. use photo
    if (files.photo) {
      if (files.photo.size > 1000000) {
        return res.status(400).json({
          errors: [{ msg: 'Image could not be uploaded. File to big.' }],
        });
      }
      //this relates to data in schema product
      project.photo.data = fs.readFileSync(files.photo.path);
      project.photo.contentType = files.photo.type;
    }
    project.save();
    console.log('project backend', project);
    return res.json(project);
  });
};

I am using formidable for photo upload. not sure why this stopped working

shivetay
  • 315
  • 4
  • 14

1 Answers1

0

I'm not familiar with Formidable, but this may help with troubleshooting the issue.

Since it is working successfully in PostMan, have you tried setting other responses based on their response code ex. res.status(200).json({success: true}) in order to troubleshoot the back end?

I have done this with Express projects in the past and it makes it a lot easier for me to find exactly where the problem is. When I find where I start to see the error, I always work backwards from there until I find the issue.

Proper way to set response status and JSON content in a REST API made with nodejs and express