首页 > 解决方案 > how can I get form data from react to node.js?

问题描述

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'),
);

标签: node.jsreactjsaxiosfetch

解决方案


您的目标/main是所有客户端调用,但在服务器上您只有/路由。

尝试以下操作:

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

或者 - 更改服务器路由:

mainRouter.post(
  '/main',
  (req, _res, _next) => console.log(req, 'req.body'),
);

推荐阅读