首页 > 解决方案 > 不知道为什么我的 app.get 运行了两次?

问题描述

我有一个app.getwhich 里面有相当多的逻辑。除了某些由于某种原因被调用两次的逻辑之外,一切都很好。我注意到当我将某些内容保存到 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');
  }

});

标签: javascriptnode.jsshopify

解决方案


推荐阅读