title: 400 BAD REQUEST when POST using Axios in React with Nodejs/Express
body: <p>I use Axios with React to use POST method to my Nodejs server. The first time I tried it gave me an error regarding CORS policy. And I have added the header to it but still it gives me status code of 400 mentioning this:</p>
  
  <pre><code>xhr.js:166 POST http://localhost:3000/api/user/register 400 (Bad Request)
  dispatchXhrRequest  @   xhr.js:166
  xhrAdapter  @   xhr.js:16
  dispatchRequest @   dispatchRequest.js:49
  Promise.then (async)        
  request @   Axios.js:56
  wrap    @   bind.js:11
  handleFormSubmit    @   Register.js:21
  onClick @   Register.js:69
  callCallback    @   react-dom.development.js:363
  invokeGuardedCallbackDev    @   react-dom.development.js:412
  invokeGuardedCallback   @   react-dom.development.js:465
  invokeGuardedCallbackAndCatchFirstError @   react-dom.development.js:480
  executeDispatch @   react-dom.development.js:613
  executeDispatchesInOrder    @   react-dom.development.js:638
  executeDispatchesAndRelease @   react-dom.development.js:743
  executeDispatchesAndReleaseTopLevel @   react-dom.development.js:752
  forEachAccumulated  @   react-dom.development.js:724
  runEventsInBatch    @   react-dom.development.js:769
  runExtractedPluginEventsInBatch @   react-dom.development.js:915
  handleTopLevel  @   react-dom.development.js:5866
  batchedEventUpdates$1   @   react-dom.development.js:24314
  batchedEventUpdates @   react-dom.development.js:1460
  dispatchEventForPluginEventSystem   @   react-dom.development.js:5966
  attemptToDispatchEvent  @   react-dom.development.js:6083
  dispatchEvent   @   react-dom.development.js:5986
  unstable_runWithPriority    @   scheduler.development.js:818
  runWithPriority$2   @   react-dom.development.js:12259
  discreteUpdates$1   @   react-dom.development.js:24331
  discreteUpdates @   react-dom.development.js:1485
  dispatchDiscreteEvent   @   react-dom.development.js:5949
  
  
  
  
  
  Error: Request failed with status code 400
      at createError (createError.js:17)
      at settle (settle.js:19)
      at XMLHttpRequest.handleLoad (xhr.js:60)
  
  </code></pre>
  
  <p><br>I was using JWT for my Auth which I wrote in Nodejs - runs on port 5000
  <br>React - runs on port 3000
  <br>I've my some othe features written in PHP - runs on port 8000</p>
  
  <p>Here, when I used React Axios with PHP it worked fine after satisfying the CORS policy. But when I did it to Nodejs I get this error. Nodejs Auth code works fine, when I tried with POSTMAN.</p>
  
  <p>Here's my React code which runs on port 3000</p>
  
  <pre><code>import React, { Component } from 'react'
  import axios from 'axios'
  
  class Register extends Component {
      constructor(props) {
          super(props)
          this.state = {
              name: "",
              email: "",
              password: "",
          }
  
      }
  
      handleFormSubmit(e) {
          e.preventDefault();
  
  
          const registerData = JSON.stringify(this.state);
  
          axios({
              method: 'POST',
              url: 'http://localhost:5000/api/user/register',
              headers: {
                  'Content-Type': 'application/json',
                      },
              data: registerData,
          })
              .then(result =&gt; {
                  console.log(registerData)
              })
              .catch(error =&gt; console.log(error))
      }
      render() {
          return (
              &lt;div&gt;
                  Register
                  &lt;br/&gt;
                  &lt;form action="#"&gt;
                      &lt;label&gt;Full Name&lt;/label&gt;&lt;br/&gt;
                      &lt;input
                          type='text'
                          id='name'
                          name='name'
                          value={this.props.name}
                          onChange={e =&gt; this.setState({ name: e.target.value })} /&gt;
                      &lt;br /&gt;
  
                      &lt;label&gt;Email&lt;/label&gt;&lt;br /&gt;
                      &lt;input
                          type='text'
                          id='email'
                          name='email'
                          value={this.props.email}
                          onChange={e =&gt; this.setState({ email: e.target.value })} /&gt;
                      &lt;br /&gt;
  
                      &lt;label&gt;Password&lt;/label&gt;&lt;br /&gt;
                      &lt;input
                          type='password'
                          id='password'
                          name='password'
                          value={this.props.password}
                          onChange={e =&gt; this.setState({ password: e.target.value })} /&gt;
                      &lt;br /&gt;
  
                      &lt;input
                          type='submit'
                          onClick={e =&gt; this.handleFormSubmit(e)} /&gt;
                      &lt;br /&gt;
                  &lt;/form&gt;
              &lt;/div&gt;
          )
      }
  }
  
  export default Register
  
  </code></pre>
  
  <p>This is the package.json I've on React:</p>
  
  <pre><code>{
    "name": "dontbuy",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
      "axios": "^0.19.0",
      "react": "^16.10.0",
      "react-dom": "^16.10.0",
      "react-native": "^0.61.1",
      "react-native-web": "^0.11.7",
      "react-router-dom": "^5.1.1",
      "react-scripts": "3.1.2"
    },
    "scripts": {
      "start": "react-scripts start",
      "build": "react-scripts build",
      "test": "react-scripts test",
      "eject": "react-scripts eject"
    },
    "eslintConfig": {
      "extends": "react-app"
    },
    "browserslist": {
      "production": [
        "&gt;0.2%",
        "not dead",
        "not op_mini all"
      ],
      "development": [
        "last 1 chrome version",
        "last 1 firefox version",
        "last 1 safari version"
      ]
    },
    "proxy": "http://localhost:5000"
  }
  </code></pre>
  
  <p>And here's my Nodejs code which runs on port 5000: (All my routes has a prefix of api/user/* )</p>
  
  <pre><code>const router = require('express').Router();
  const User = require('../model/User');
  const bcrypt = require('bcryptjs');
  const { registerValidation, loginValidation } = require('../validation')
  const jwt = require('jsonwebtoken');
  
  //API response
  router.post('/register' , async (req, res) =&gt; {
  
  
      //validating the response
      const { error } = registerValidation(req.body);
      if(error){
          return res.status(400).send(error);
      }
  
      //Check the user is already in the db
      const emailExists = await User.findOne({email: req.body.email});
      if(emailExists){
          return res.status(400).json({"message" : "Email already exists"});
      }
  
      //Hashing the password
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(req.body.password, salt);
  
      //Creating a new user
          const user = new User({
              name: req.body.name,
              email: req.body.email,
              password: hashedPassword,
          })
          try {
              const savedUser = await user.save();
              res.send({ user: user._id });
          } catch (err) {
              res.status(400).send(err);
          }  
  })
  
  
  //Login
  
  router.post('/login', async (req, res) =&gt; {
      //validation
      const { error } =loginValidation(req.body);
      if(error){
          return res.status(400).send(error.details[0].message);
      }
      //check if the email is already exists
      const user = await User.findOne({ email: req.body.email });
      if (!user) {
          return res.status(400).json({"message": "Email or password is incorrect"});
      }
      const validPassword = await bcrypt.compare(req.body.password, user.password);
      //check if password is correct
      if(!validPassword) {
          return res.status(400).json({"message" :"Password is incorrect"});
      }
      //create and assign a token
      const token = jwt.sign({_id: user._id}, 'secretKey');
      res.header('auth-token', token).send(token);
  
      res.send('Logged in')
  })
  
  
  module.exports = router;
  </code></pre>