Express does not receive parameters via POST from React using Fetch API

Viewed 3425

I'm developing a simple app using Express.js and React, both applications in the development environment (local machine) are on different ports, the server (Express) on localhost: 3001 and the Frontend (React) on localhost: 3000.

The problem I have is that trying to send data from the Frontend using Fetch API Express does not receive the data sent via POST by React. I did a test doing a POST from a normal form and the server did accept the parameters I send via POST, so I think the problem is something with the call from Javascript using Fetch API.

In Express I already installed the cors module to accept requests that are not of the same domain but the problem persists.

Below is a snippet of code from both for a better understanding.

...
// handler recieves the 'e' event object
formPreventDefault(e) {
    var headers = new Headers();
    headers.append('Accept', 'application/json, application/xml, text/plain, text/html, *.*');
    headers.append('Content-Type', 'multipart/form-data; charset=utf-8');
    headers.append('Access-Control-Allow-Origin', '*');
    headers.append('Access-Control-Allow-Headers', 'Content-Type');

    var myForm = document.getElementById('myForm');
    var formData = new FormData(myForm);
    formData.append('email', 'demo@domain.com');
    formData.append('password', '12345');

        var options = {
        headers: headers,
        mode: 'no-cors', // crossdomain *
        method: 'post',
        body:  JSON.stringify({ 'email': 'admin@domain.com', 'password': '12345' }) // formData
    };

    var request = new Request('http://localhost:3001/user/signin', options);

    fetch(request).then(function(response) {
        console.log("Success");
        return response;
    }).then(function(json) {
        console.log(json);
        }).catch(function(err) {
        console.log("Error " + err);
    })

    // prevent submit form
    e.preventDefault();

  }

  render() {
    return (
      <div className="row">
        <div className="col-md-4  ">
          <form id="myForm" action="http://localhost:3001/user/signin" method="post" onSubmit={this.formPreventDefault}>
                <div className="form-group">
                  <label htmlFor ="email">Email address</label>
                  <input type="email" className="form-control" id="email" name="email" placeholder="Email" />
                </div>
                <div className="form-group">
                  <label htmlFor ="password">Password</label>
                  <input type="password" className="form-control" id="password" name="password" placeholder="*******" />
                </div>
                <button type="submit" className="btn btn-default">Submit</button>
              </form>
        </div>
      </div>
    );
  }
}
...

Express Controller

...
// Handle User Sign In on POST
exports.user_create_post = function(req, res) {
    console.log(req.body); // This always returns an empty value
    //Check that the name field is not empty
    req.checkBody('email', 'Email address is required').notEmpty();
    req.checkBody('password', 'Password is required').notEmpty();

    //Run the validators
    var errors = req.validationErrors();

    //Create a genre object with escaped and trimmed data.
    var user = new User(
      { email: req.body.email, password: req.body.password }
    );

    if (errors) {
        //If there are errors render the form again, passing the previously entered values and errors
        // res.render('users/sign_up', { title: 'Sign Up', user: user, errors: errors });
        res.json({ user: user, errors: errors });
        return;
    }
    else {
        // Data from form is valid.
        //Check if User with same email already exists if not the new user is saved
        User.findOne({ 'email': req.body.email })
            .exec( function(err, found_user) {
                 if (err) { return next(err); }

                 if (found_user) {
                     //User exists, redirect to the home page
                     // res.render('users/home', { title: 'Home', user: found_user });
                     res.json({ user: found_user });
                 }
                 else {
                    // Save user
                     user.save(function (err) {
                       if (err) { return next(err); }

                       // Create session
                       req.session.user_id = user._id.toString();

                       // User saved. Display user profile page
                       // res.render('users/home', { title: 'Home', user: user });
                       res.json({ user: user });
                     });

                 }

             });
    }
};
...

Any help is welcome

3 Answers
Related