无法弄清楚为什么我的app.get被运行两次?

时间:2018-09-13 01:27:45

标签: javascript node.js shopify

我有一个app.get,里面有很多逻辑。除了某些出于某种原因两次被调用的逻辑之外,其他所有方法都可以正常工作。我注意到当我将某些内容保存到db时,它将保存两行。

因此,我在该区域中放置了一个console.log,并确保它记录了两次。

为什么会这样?

app.get('/shopify/callback', (req, res) => {

  const { shop, hmac, code, state } = req.query;
  const stateCookie = cookie.parse(req.headers.cookie).state;

  if (state !== stateCookie) {
    return res.status(403).send('Request origin cannot be verified');
  }

  if (shop && hmac && code) {

    // DONE: Validate request is from Shopify
    const map = Object.assign({}, req.query);
    delete map['signature'];
    delete map['hmac'];
    const message = querystring.stringify(map);
    const providedHmac = Buffer.from(hmac, 'utf-8');
    const generatedHash = Buffer.from(
      crypto
        .createHmac('sha256', config.oauth.client_secret)
        .update(message)
        .digest('hex'),
        'utf-8'
      );
    let hashEquals = false;

    try {
      hashEquals = crypto.timingSafeEqual(generatedHash, providedHmac)
    } catch (e) {
      hashEquals = false;
    };

    if (!hashEquals) {
      return res.status(400).send('HMAC validation failed');
    }

    // DONE: Exchange temporary code for a permanent access token
    const accessTokenRequestUrl = 'https://' + shop + '/admin/oauth/access_token';
    const accessTokenPayload = {
      client_id: config.oauth.api_key,
      client_secret: config.oauth.client_secret,
      code,
    };

    request.post(accessTokenRequestUrl, { json: accessTokenPayload })
    .then((accessTokenResponse) => {

      const accessToken = accessTokenResponse.access_token;
      // DONE: Use access token to make API call to 'shop' endpoint
      const shopRequestUrl = 'https://' + shop + '/admin/shop.json';
      const shopRequestHeaders = {
        'X-Shopify-Access-Token': accessToken,
      }

     request.get(shopRequestUrl, { headers: shopRequestHeaders })
      .then((shopResponse) => {

        const response = JSON.parse(shopResponse);
        const shopData = response.shop;

        console.log('BEING CALLED TWICE...')

        res.render('pages/brand_signup',{
          shop: shopData.name
        })

      })
      .catch((error) => {
        res.status(error.statusCode).send(error.error.error_description);
      });


    })
    .catch((error) => {
      res.status(error.statusCode).send(error.error.error_description);
    }); 


  } else {
    res.status(400).send('Required parameters missing');
  }

});

0 个答案:

没有答案