title: How to fix 'TypeError: Failed to fetch'?
body: <p>I'm getting a <code>TypeError: Failed to fetch</code> error when I attempt to send a post request using <code>fetch</code> on the front-end and an express route on the back-end.</p>
  
  <p>I'm able to successfully create the new user in the db, but when attempting to obtain that new user data through the fetch promise, that's when the error is being thrown.</p>
  
  <p><strong>app.js</strong></p>
  
  <pre><code>function createNewUser() {
    let formUsername = document.getElementById('signup-username').value;
    let formEmail = document.getElementById('signup-email').value;
    let formPassword = document.getElementById('signup-password').value;
    let url = "/users";
    let newUserData = {
      username: formUsername,
      email: formEmail,
      password: formPassword
    }
  
    fetch(url, {
      method: 'POST',
      cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
      credentials: 'same-origin', // include, *same-origin, omit
      headers: {
          'Content-Type': 'application/json'
      },
      redirect: 'follow', // manual, *follow, error
      referrer: 'no-referrer',
      body: JSON.stringify(newUserData),
    }).then(res =&gt; res.json())
    .then(response =&gt; console.log('Success: ', JSON.stringify(response)))
    .catch(error =&gt; console.error('Error: ', error));
  }
  </code></pre>
  
  <p><strong>users.js</strong></p>
  
  <pre><code>router.post('/users', function(req, res) {
     User.create(req.body)
     .then(function(user) {
        res.json({
           user: user
        })
     }
  });
  </code></pre>
  
  <p><strong>server.js</strong></p>
  
  <pre><code>const express = require('express');
  const app = express();
  const fs = require('fs');
  const path = require('path');
  const bodyParser = require('body-parser');
  const bcrypt = require('bcryptjs');
  const auth = require('./auth');
  const router = require('./routes/routes.js');
  
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(router);
  
  app.use('/', express.static(path.join(__dirname, 'public')));
  
  app.use((req, res, next) =&gt; {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader(
      "Access-Control-Allow-Methods",
      "OPTIONS, GET, POST, PUT, PATCH, DELETE" // what matters here is that OPTIONS is present
    );
    res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization", "Access-Control-Allow-Origin");
    next();
  });
  
  app.listen(3000, function(){
    console.log("Listening on port 3000");
  });
  
  </code></pre>
  
  <p>I need to get that user object back in order to access its data.</p>
  
  <p><strong>Edit:</strong>
  So, I've figured out that the issue has to do with how the request is submitted on the front-end. If I create the following function and then call it when <code>app.js</code> is loaded, then everything works:</p>
  
  <pre><code>function createNewUserTest() {
    let formUsername = 'dd';
    let formEmail = 'd@d.com';
    let formPassword = 'secrete';
    let url = "/api/users";
    let newUserData = {
      username: formUsername,
      email: formEmail,
      password: formPassword
    }
    fetch(url, {
      method: 'POST',
      cache: 'no-cache',
      credentials: 'same-origin',
      headers: {
          'Content-Type': 'application/json'
      },
      body: JSON.stringify(newUserData),
    })
    .then(res =&gt; res.json())
    .then(response =&gt; console.log('Success: ', response))
    .catch(error =&gt; console.error('Error: ', error));
  }
  
  createNewUserTest();
  </code></pre>
  
  <p>But, if I try to call this function either through <code>onsubmit</code> in the form or <code>onclick</code> on the button in the html, or if I use an event listener (see below, which is in <code>app.js</code>), then I get the <code>TypeError: Failed to fetch</code> error:</p>
  
  <pre><code>let signupSubmitButton = document.getElementById('signup-submit');
  signupSubmitButton.addEventListener('click', createNewUserTest);
  </code></pre>
  
  <p>This is even more baffling to me. I'm required to use Vanilla JS and I need to create the user through a form submission, but not sure what I need to adjust here.</p>
  
  <p><strong>Solution</strong>
  Foiled by the <code>event.preventDefault()</code> again. This was all I needed.</p>
  
  <pre><code>let signupForm = document.getElementById('signup-form');
  signupForm.addEventListener('submit', function(event) {
    event.preventDefault();
    let formUsername = document.getElementById('signup-username').value;
    let formEmail = document.getElementById('signup-email').value;
    let formPassword = document.getElementById('signup-password').value;
    let url = "/api/users";
    let newUserData = {
      username: formUsername,
      email: formEmail,
      password: formPassword
    }
    fetch(url, {
      method: 'POST',
      cache: 'no-cache',
      credentials: 'same-origin',
      headers: {
          'Content-Type': 'application/json'
      },
      body: JSON.stringify(newUserData),
    })
    .then(res =&gt; res.json())
    .then(response =&gt; console.log('Success: ', response))
    .catch(error =&gt; console.error('Error: ', error));
  });
  </code></pre>