0

I am trying to send the form data of react component to the server through using axios or fetch. All of the code I wrote failed (in onSubmit). My server's port is 5000. I have already set bodyParser in server.js as well.

app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));

// React Component

const Voting = ({ history }) => {
  const [hasQuery, setQuery] = useState('');

  const [formData, setFormData] = useState({
    cat: false,
    dog: false,
  });

  const { cat, dog } = formData;

  const onChange = e => {
    let obj = {};

    obj[e.target.name] = e.target.checked;
    setFormData(obj);
  };

  const onSubmit = async e => {
    e.preventDefault();
     
    1. 
    // axios.post('http://localhost:5000/main', { formData }).then(result => {
    //   console.log(result, 'result');
    // });

    2. 
    fetch('http://localhost:5000/main', {
      method:'post',
      body: formData
    })
    .then(res => res.json())
    .then(data => alert(data.msg));

    3.
    // fetch('http://localhost:5000/main', {
    //   method: 'post',
    //   headers: {
    //     'Content-Type': 'application/json; charset=utf-8'
    //   },
    //   body: JSON.stringify(formData),
    // })
    //   .then(res => res.json())
    //   .then(obj => {
    //     if (obj.result === 'succ') {
    //       alert('Move on to the next.');
    //     }
    //   });

    history.push(`/success`);
  };

  return (
    <div>
      <p>{hasQuery}</p>
      <form
        className='mode-container'
        onSubmit={onSubmit}
        mathod='POST'
        action='http://localhost:5000/main'
      >
        <h3>Choose what you like more</h3>
        <div>
          <label>
            cat
            <input
              type='radio'
              name='cat'
              value={cat}
              onChange={onChange}
            />
          </label>
          <label>
            dog
            <input
              type='radio'
              name='dog'
              value={dog}
              onChange={onChange}
            />
          </label>
        </div>
        <button type='submit'></button>
      </form>
    </div>
  );
};

const mapStateToProps = state => ({
  isAuthenticated: state.auth.isAuthenticated,
});

export default connect(mapStateToProps)(Voting);

And below is the code I wrote in node.js. req.body is an empty object.

// Node.js

mainRouter.post(
  '/',
  (req, _res, _next) => console.log(req, 'req.body'),
);
1
  • What is the error that you get ?? Commented Nov 3, 2020 at 11:49

1 Answer 1

0

You are targeting /main in all of your client calls, but on server you only have / route.

Try the following:

axios.post('http://localhost:5000/', { formData }).then(result => {
  console.log(result, 'result');
});

Or - change the server route:

mainRouter.post(
  '/main',
  (req, _res, _next) => console.log(req, 'req.body'),
);
Sign up to request clarification or add additional context in comments.

1 Comment

I did in server.js app.use('/main', mainRouter); and then routes/main folder mainRouter.post( '/', (req, _res, _next) => console.log(req, 'req.body'), );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.