【问题标题】:Github webhook with NextJs带有 NextJs 的 Github webhook
【发布时间】:2020-03-22 15:35:08
【问题描述】:

我正在处理一个 NextJS 项目,我想使用 github webhook 来部署一个包含部署说明的脚本。

我已经在 github 中设置了一个推送 webhook

我尝试在 server.ts 文件中添加以下代码,现在使用 ngrok 进行测试

// testing
server.post("/webhooks/github", function(req, res) {
  var sender = req.body.sender;
  var branch = req.body.ref;

  if (branch.indexOf("master") > -1 && sender.login === githubUsername) {
    deploy(res);
  }
});

function deploy(res: any) {
  childProcess.exec("sh deploy.sh", function(err, stdout, stderr) {
    if (err) {
      console.error(err, stderr);
      return res.send(500);
    }
    console.log(stdout);
    res.send(200);
  });
}

这个文件是我的 nextJS 应用程序的节点文件

但是我在我的 ngrok 日志中得到 502

我想知道我应该将这个 webhook 端点放在我的 NextJS 应用程序的哪个位置以使其工作

【问题讨论】:

    标签: express github next.js


    【解决方案1】:

    我知道这已经晚了,但这对我有用:

    // pages/api/webhooks/github.js
    const { exec } = require("child_process");
    const crypto = require("crypto");
    
    // Handle GitHub Webhooks
    export default function handler(req, res) {
        try {
            console.log("Incoming Request");
            if (req.method !== 'POST') {
                res.send(404);
                return;
            }
            let sig =
                "sha256=" +
                crypto
                    .createHmac("sha256", process.env.WEBHOOKS_SECRET)
                    .update(JSON.stringify(req.body))
                    .digest("hex");
            if (
                req.headers["x-hub-signature-256"] === sig &&
                req.body?.ref === "refs/heads/main" &&
                process.env.REPO_PATH
            ) {
                exec(
                    "cd " +
                        process.env.REPO_PATH +
                        " && git pull && npm install && npm run build && pm2 restart app"
                );
                console.log("GitHub Webhook ran successfully");
                res.end();
                return;
            }
            console.log("GitHub Webhook failed");
            res.end();
            return;
        } catch (e) {
            console.log(e);
        }
    };
    

    【讨论】:

      【解决方案2】:

      我可以让它工作的唯一方法是在同一台服务器上创建另一个应用程序(我使用 express),然后在该服务器上使用一个端点作为 github webhook,然后我从那里运行部署脚本。

      简单的解决方案,希望这对某人有所帮助..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-26
        • 2021-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-15
        相关资源
        最近更新 更多