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


i'm developing simple app using express.js , react, both applications in development environment (local machine) on different ports, server (express) on localhost: 3001 , frontend (react) on localhost: 3000.

the problem have trying send data frontend using fetch api express not receive data sent via post react. did test doing post normal form , server did accept parameters send via post, think problem call javascript using fetch api.

in express installed cors module accept requests not of same domain problem persists.

below snippet of code both better understanding.

... // handler recieves '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); // returns empty value     //check name field not empty     req.checkbody('email', 'email address required').notempty();     req.checkbody('password', 'password required').notempty();      //run validators     var errors = req.validationerrors();      //create genre object escaped , trimmed data.     var user = new user(       { email: req.body.email, password: req.body.password }     );      if (errors) {         //if there errors render form again, passing entered values , errors         // res.render('users/sign_up', { title: 'sign up', user: user, errors: errors });         res.json({ user: user, errors: errors });         return;     }     else {         // data form valid.         //check if user same email exists if not new user saved         user.findone({ 'email': req.body.email })             .exec( function(err, found_user) {                  if (err) { return next(err); }                   if (found_user) {                      //user exists, redirect 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 welcome

your primary problem aren't setting request body form data. instead manually encoding form data json. big tipoff: create formdata variable never use anywhere.

try this:

options = {     headers: headers,     mode: 'no-cors', // crossdomain *     method: 'post',     body:  formdata }; 

Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -