title: Creating middleware that does external api call
body: <p>I'm creating a middleware that checks if a JWT token is valid, to do this it needs to call an external API. If the token is valid, it should continue the regular functionality.</p>
  
  <p>Here's the <strong>middleware</strong> I wrote (<code>then</code> does not get triggered):</p>
  
  <pre><code>app.use(function(req, res, next) {
    if (!req.headers.authorization) {
      return res.status(401).json({
        status: 401,
        message: 'Unauthorized Error: Invalid access token.'
      }).end();
    } else {
      requestify
        .request(process.env.SWF_AUTH_INFO, {
          method: 'GET',
          headers: {
            'Accept-Language': 'nl',
            Authorization: req.headers.authorization
          }
        })
        .then(function(response) {
          if (response.body.valid) {
            next();
          } else {
            return res.status(401).json({
              status: 401,
              message: 'Unauthorized Error: Invalid access token.'
            }).end();
          }
        });
    }
  });
  </code></pre>
  
  <p><strong>My problem:</strong></p>
  
  <p>Every call I do just stays on <code>pending</code>. I don't get any response and I don't get any errors either. All my calls worked perfectly before I wrote the middleware.</p>
  
  <p>Here's how I handle my api requests:</p>
  
  <p><strong>Route</strong></p>
  
  <pre><code>/**
     * Get all surveys associated with a participant
     *
     * URL: /participant/:id/surveys
     * METHOD: GET
     */
    router.get('/participant/:id/surveys', function(req, res) {
      if (!req.params.id) {
        return res.status(422).send('Participant id of null');
      }
      participantService
        .getSurveys(req.params.id)
        .then(data =&gt; {
          res.status(200).send(data);
        })
        .catch(err =&gt; {
          res.status(422).send(err);
        });
    });
  </code></pre>
  
  <p><strong>Service:</strong></p>
  
  <pre><code>function getSurveys(participantId) {
    return participantModel.getSurveys(participantId);
  }
  </code></pre>
  
  <p><strong>Model:</strong></p>
  
  <pre><code>function getSurveys(participantId) {
    return new Promise((resolve, reject) =&gt; {
      db.query(
          ...
        ),
        (error, result) =&gt; {
          if (error) {
            dbFunc.connectionRelease;
            reject(error);
          } else {
            dbFunc.connectionRelease;
            resolve(result);
          }
        }
      );
    });
  }
  </code></pre>
  
  <p>Why is my middleware not sending any responses?</p>