title: ReactJS and Node -- Error 400 bad request
body: <p>I am trying to build a react application which saves data into database.</p>
  
  <p>I have the following classes:</p>
  
  <p><strong>server.js</strong></p>
  
  <pre><code>let express = require('express');
  let bodyParser = require('body-parser');
  let morgan = require('morgan');
  let pg = require('pg');
  let cors = require('cors');
  const PORT = 3000;
  
  let pool = new pg.Pool({
      user: 'admin',
      database: 'dev',
      password: 'password',
      host: 'localhost',
      port: 5432,
      max: 10
  });
  
  let app = express();
  app.use(cors());
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));
  
  app.use(morgan ('dev'));
  
  app.use(function(request, response, next) {
      response.header("Access-Control-Allow-Origin", "*");
      response.header("Access-Control-Allow-Headers", "Origin, X-Requested-
  With, Content-Type, Accept, Authorization")
  next();
  });
  
  app.get('/api/creditcards', function(request, response) {
  pool.connect(function(err, db, done) {
      if (err) {
          return response.status(400).send(err);
      } else {
          db.query('SELECT * FROM creditcards', function(err, table) {
              done();
              if (err) {
                  response.status(400).send(err)
              }else {
                  response.status(200).send(table.rows)
              }
          })
      }
  })
  });
  
  app.post('/api/new-card', function(request, response) {
      var cardholder = request.body.cardholder;
      var cardnumber = request.body.cardnumber;
      var card_identifier = request.body.card_identifier;
      var expiration = request.body.expiration;
      var cvc = request.body.cvc;
  
    let values = [cardholder, cardnumber, card_identifier, expiration, cvc];
  
    pool.connect((err, db, done) =&gt; {
      if(err) {
          return response.status(400).send(err);
          } else {
              db.query('INSERT INTO creditcards (cardholder, cardnumber, card_identifier, expiration, cvc) VALUES ($1, $2, $3, $4, $5)', [cardholder, cardnumber, card_identifier, expiration, cvc] ,(err, table) =&gt; {
                  done();
                  if (err) {
                      return response.status(400).send(err)
                      } else {
                          console.log('DATA INSERTED');
                          response.status(201).send({message : 'Data inserted...'})
                          }
                  })
              }
  })
  });
  
  app.listen(PORT, () =&gt; console.log('Listening on port ' + PORT));
  </code></pre>
  
  <p>and <strong>SaveNewCard.js</strong></p>
  
  <pre><code>import React from 'react';
  import Modal from './Modal';
  import Payment from 'payment';
  import { Row, Col, FormGroup, ControlLabel, Button, Alert, Grid } from 'react-bootstrap';
  
  class SaveNewCard extends React.Component {
      constructor() {
      super();
  
      this.state = {
          creditcards: [],
          isLoading: false,
          error: null,
      }
    }
  
    componentDidMount() {
    const { cardnumber, expiration, cvc } = this.refs;
          Payment.formatCardNumber(cardnumber);
          Payment.formatCardExpiry(expiration);
          Payment.formatCardCVC(cvc);
    console.log('Component has mounted')
  var that = this;
  fetch('http://localhost:3000/api/creditcards')
              .then(response =&gt; {
              console.log(response)
                 if (response.ok) {
                    return response.json();
                 } else {
                     throw new Error('Something went wrong ...');
                  }
                 })
                  .then(data =&gt; that.setState({ creditcards: data.creditcards, isLoading: false }))
                  .catch(error =&gt; this.setState({ error, isLoading: false }));
              }
  
  
  addCreditCard(event) {
    var that = this;
    event.preventDefault();
    let card_data = {
      cardholder : this.refs.cardholder.value,
      cardnumber : this.refs.cardnumber.value,
      card_identifier : (this.refs.cardnumber.value).substr(15),
      expiration : this.refs.expiration.value,
      cvc : this.refs.cvc.value
  };
  console.log('Ez itt: ' + JSON.stringify(card_data))
  var request = new Request('http://localhost:3000/api/new-card', {
      method: 'POST',
      headers: new Headers({ 'Content-Type': 'application/json',  }),
      body: JSON.stringify(card_data)
  });
  let creditcards = that.state.creditcards;
        creditcards.push(card_data);
          that.setState({
           creditcards : creditcards
  })
  
  console.log(creditcards)
  
  fetch(request)
      .then(response =&gt; {
       console.log(request)
         if (response.ok) {
           return response.json();
         } else {
            throw new Error('Something went wrong ...');
         }
       })
         .then(data =&gt; this.setState({ creditcards: data.creditcards }))
         .catch(error =&gt; this.setState({ error }));
    }
  
  
    cardList() {
          return (&lt;ul className="credit-card-list clearfix"&gt;
            &lt;Alert fluid style={{ paddingLeft: 40}} bsStyle="warning"&gt;
               &lt;strong&gt;Please consider that only the following credit cards can be accepted:&lt;/strong&gt;
            &lt;li&gt;&lt;i data-brand="visa" className="fa fa-cc-visa"&gt;VISA&lt;/i&gt;&lt;/li&gt;
            &lt;li&gt;&lt;i data-brand="amex" className="fa fa-cc-amex"&gt;AMEX&lt;/i&gt;&lt;/li&gt;
            &lt;li&gt;&lt;i data-brand="mastercard" className="fa fa-cc-mastercard"&gt;Master Card&lt;/i&gt;&lt;/li&gt;
            &lt;/Alert&gt;
          &lt;/ul&gt;);
        }
  
      saveNewCardForm() {
      let creditcards = this.state.creditcards;
              return (
              &lt;div&gt;
                  &lt;form className="SaveNewCard" onSubmit={ this.handleSubmit } style={{ paddingLeft: 40, paddingRight: 600}}&gt;
                      &lt;Grid fluid style={{ paddingLeft: 60, paddingRight: 60}}&gt;
                      &lt;Row&gt;
                       &lt;Col xs={12}&gt;
                         &lt;FormGroup&gt;
                           &lt;ControlLabel&gt;Cardholder Name&lt;/ControlLabel&gt;
                              &lt;input
                                onKeyUp= {this.setCardType}
                                className="form-control text-center"
                                type="text"
                                ref="cardholder"
                                placeholder="Your Name"
                              /&gt;
                          &lt;/FormGroup&gt;
                         &lt;/Col&gt;
                        &lt;/Row&gt;
                        &lt;Row&gt;
                          &lt;Col xs={ 12 }&gt;
                            &lt;FormGroup&gt;
                              &lt;ControlLabel&gt;Card Number&lt;/ControlLabel&gt;
                              &lt;input
                                onKeyUp={ this.setCardType }
                                className="form-control text-center"
                                type="text"
                                ref="cardnumber"
                                placeholder="Card Number"
                              /&gt;
                            &lt;/FormGroup&gt;
                          &lt;/Col&gt;
                        &lt;/Row&gt;
                        &lt;/Grid&gt;
                        &lt;Grid fluid style={{ paddingLeft: 60, paddingRight: 60}}&gt;
                        &lt;Row &gt;
                          &lt;Col xs={ 6 } sm={ 5 }&gt;
                            &lt;FormGroup&gt;
                              &lt;ControlLabel&gt;Expiration&lt;/ControlLabel&gt;
                              &lt;input
                                className="form-control text-center"
                                type="text"
                                ref="expiration"
                                placeholder="MM/YYYY"
                              /&gt;
                            &lt;/FormGroup&gt;
                          &lt;/Col&gt;
                          &lt;Col xs={ 6 } sm={ 4 } smOffset={ 3 }&gt;
                            &lt;FormGroup&gt;
                              &lt;ControlLabel&gt;CVC&lt;/ControlLabel&gt;
                              &lt;input
                                className="form-control text-center"
                                type="text"
                                ref="cvc"
                                placeholder="CVC"
                              /&gt;
                            &lt;/FormGroup&gt;
                          &lt;/Col&gt;
                        &lt;/Row&gt;
                        &lt;/Grid&gt;
                      &lt;Button bsStyle="primary" onClick={this.addCreditCard.bind(this)}&gt;Submit&lt;/Button&gt;
                      &lt;Button onClick={this.removeCreditCard.bind(this)}&gt;Delete&lt;/Button&gt;
                      &lt;/form&gt;
                      &lt;ul&gt;
                          {creditcards.map((creditcards =&gt; &lt;li&gt;{creditcards.cardholder}&lt;/li&gt;))}
                      &lt;/ul&gt;
                      &lt;/div&gt;);
          }
  
          render() {
                    return (&lt;div className="CreditCard"&gt;
                      { this.cardList() }
                      { this.saveNewCardForm() }
                    &lt;/div&gt;);
                  }
  
  }
  
  SaveNewCard.propTypes = {};
  
  
  export default SaveNewCard;
  </code></pre>
  
  <p>But I got the following Bad Request 400 error:</p>
  
  <p><a href="https://i.stack.imgur.com/Z1Fv3.jpg" rel="noreferrer">enter image description here</a></p>
  
  <p>And:</p>
  
  <p><a href="https://i.stack.imgur.com/X3h9K.jpg" rel="noreferrer">enter image description here</a></p>
  
  <p>As I can understand, my request does not contain the inserted data...
  I assume the problem is here somewhere....:</p>
  
  <p><a href="https://i.stack.imgur.com/jLOrt.jpg" rel="noreferrer">enter image description here</a></p>
  
  <p>I let to write the "card_data" content to the console, it is there:</p>
  
  <p><a href="https://i.stack.imgur.com/1mEup.jpg" rel="noreferrer">enter image description here</a></p>
  
  <p>Any idea, why am I getting nulls as input data?</p>
  
  <p>Sorry for this long post....</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>The code fails at this line:</p>
  
  <p><a href="https://i.stack.imgur.com/VvTbt.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/VvTbt.jpg" alt="enter image description here"></a></p>
  
  <p>I replaced the "request.body.XY" variables with direct input and in that case the insert to database was working.... It may something with my request...</p>
  
  <p><a href="https://i.stack.imgur.com/aDEQy.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/aDEQy.jpg" alt="enter image description here"></a></p>