React app will not handle Post properly

React app will not handle Post properly
0.0 0

#1

Greetings, campers.

This is one of a series of small projects I am doing before trying to tackle the last of the back-end certification projects, and I have run into a problem where I get no errors but it is just not doing the post to the database.

Quite simply, I cannot determine why my react nodejs app is not sending the data to the mLab db.

Here is all the code: https://github.com/olddognewtrix123/lm_05

I believe the issue may be in the ‘fetch’ statement but at this point I am too much of a noob to spot the problem:

             handleSubmit: function(e){
                       e.preventDefault();
                       var newquestion = this.refs.newquestion.value;
                     fetch('/api/ninjas?name=' + newquestion ).then(function(data){
                         return data.json();
                    }).then( json => {
                        this.setState({
                             ninjas: json
                        });
                        console.log(json);
                     });
                 },

I think the answer to this will turn out to be very simple but at this point I am humbly requesting that others take a look.

Thanks!


#2

I haven’t looked at your close too closely—is it correct that you intend to use the fetch() the code snippet you posted to interact with the following part of your Node/Express server?

router.post('/ninjas', function(req, res, next){
  Ninja.create(req.body).then(function(ninja){
      res.send(ninja);
  }).catch(next);
});

If so, I think the problem is because you haven’t specified that the request’s method to be POST (the default is GET, you can verify this by logging inside the route.get route). To use fetch to interact with a post route, you need to specify the method to be so. Here is an edited example of an e-mail contact form that I made:

fetch('https://www.myproject.com/api', {
  method: 'POST',
  body: JSON.stringify({ name, email, confirmation, message }),
  headers: {"Content-Type": "application/json"}
})
.then((response) => {
  if (response.ok) {
    console.log('(◕◡◕✿)');
  }
  else {
    console.log('(╯◕︿◕)╯︵ ┻━┻ ');
  }
})

I hope that helps!


#3

THANK YOU SO MUCH! The application now posts data to mLab!

Here what the /api looks like:

  const express = require('express');

  const router = express.Router();

  const Ninja = require('../models/ninja');

  router.get('/ninjas', function(req, res, next){

      // finds everybody - keep for testing!!
      Ninja.find({}).then(function(ninjas){
          res.send(ninjas)
      })
   });  

  router.post('/ninjas', function(req, res, next){
    Ninja.create(req.body).then(function(ninja){
        res.send(ninja);
    }).catch(next);
  });

  module.exports = router;

And here is the updated component using your suggestion:

    var Child00 = React.createClass({

           getInitialState: function(){
               return({
                   newquestion: ''
               });
           },

           render: function(){
            
              return (
                   <div id="pookie00" >
                      <form id="addQandA" onSubmit={this.handleSubmit}>
                             <input type = "text" required ref="newquestion" name="newquestion" placeholder='Enter your 
    question' onChange={this.onFormChange} />
                             <input type = "submit" value={this.state.labelclick}  />
                            </form>
                        <button onClick={this.props.onClick} style={{color: 'red'}}>
                       Cancel and Close
                     </button>
                      </div>
                 );
              },
        
              //Custom functions
                     handleSubmit: function(e){
                    
                         e.preventDefault();
                         var newquestion = this.refs.newquestion.value;
                    
                        fetch('/api/ninjas', {
                           method: 'POST',
                           body: JSON.stringify({"name":newquestion}),
                               headers: {"Content-Type": "application/json"}
                         })
                         .then((response) => {
                           if (response.ok) {
                             console.log('(◕◡◕✿)');
                           }
                           else {
                             console.log('(╯◕︿◕)╯︵ ┻━┻ ');
                           }
                         })
                     },