title: Cross-Origin Request Blocked with React and Express
body: <p>So I hit this error, when I was trying to send data to the back end using React. From what I learnt I need to allow the communication on the back-end and in the <code>.htaccess</code> file. Here are some of the links I used:</p>
  
  <p><a href="https://stackoverflow.com/questions/18310394/no-access-control-allow-origin-node-apache-port-issue">No &#39;Access-Control-Allow-Origin&#39; - Node / Apache Port Issue</a></p>
  
  <p><a href="https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work">How does Access-Control-Allow-Origin header work?</a></p>
  
  <p>Both of them have code, but it didn't help.</p>
  
  <p>So far my Server-side code is this:</p>
  
  <pre><code>app.use(function (req, res, next) {
      // Website you wish to allow to connect
      // res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
  
      res.setHeader('Access-Control-Allow-Origin', '*');
  
      // Request methods you wish to allow
      res.setHeader('Access-Control-Allow-Methods', 'POST');
  
      // Request headers you wish to allow
      res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  
      // Set to true if you need the website to include cookies in the requests sent
      // to the API (e.g. in case you use sessions)
      res.setHeader('Access-Control-Allow-Credentials', true);
  
      // Pass to next layer of middleware
      next();
  });
  </code></pre>
  
  <p>This is my Client-side code:</p>
  
  <pre><code>sendMail(e) {
      e.preventDefault();
      var name = document.getElementById('name').value;
      var contactReason = document.getElementById('contactReason').value;
      var email = document.getElementById('email').value;
      var additionalInfo = document.getElementById('additionalInfo').value;
      var body = {
          name: name,
          contactReason: contactReason,
          email: email,
          additionalInfo: additionalInfo,
      };
      console.log(JSON.stringify(body));
      fetch('http://localhost:4000/', {
          method: 'POST',
          body: body,
      }).then(r =&gt; console.log(r)).catch(e =&gt; console.log(e));
  }
  </code></pre>
  
  <p>So what am I missing? I do not have an <code>.htaccess</code> file, but I'm doing it all locally so I'm not sure if I can even use it.</p>
  
  <p>It looks to me like I'm allowing all I need, but I guess it's not enough.</p>
  
  <p>If you're going to mark as a duplicate, please at least make sure my issues are covered by the answer.</p>