如何访问 Express 应用程序实例以在 Probot 应用程序中设置 CORS 来源?

How can I access the Express app instance to set CORS origin in a Probot app?

probot documentation 提到我可以像在 vanilla Express 服务器中一样使用路由。

我想为这些路由设置 CORS 来源 headers。在 vanilla Express 服务器中,我会使用 cors 包:

const cors = require('cors')

...

app.use(cors())

但是probot app没有函数use

module.exports = app => {
  app.use(cors(corsOptions));
// ...

导致错误:

ERROR (event): app.use is not a function
    TypeError: app.use is not a function

如何设置 CORS?

您必须以编程方式启动应用程序。这样您就可以在 probot 加载之后但在 Probot 启动之前访问 Express 应用 运行:

const cors = require("cors");
const bodyParser = require("body-parser");
const { Probot } = require("probot");
const { corsOptions } = require("./src/util/init-server.js");
const endpoint = require("./src/controller/endpoint");
const { handleWhatever } = require("./src/controller/controller");


// https://github.com/probot/probot/blob/master/src/index.ts#L33
const probot = new Probot({
  id: process.env.APP_ID,
  port: process.env.PORT,
  secret: process.env.WEBHOOK_SECRET,
  privateKey: process.env.PRIVATE_KEY,
  webhookProxy: process.env.WEBHOOK_PROXY_URL,
});


const probotApp = app => {
  /** Post a comment on new issue */
  app.on("issues.opened", async context => {
    const params = context.issue({ body: "Hello World!" });
    return context.github.issues.createComment(params);
  });

  /** --- Express HTTP endpoints --- */
  const router = app.route("/api");
  router.use(cors(corsOptions)); // set CORS here
  router.use(bodyParser.json());
  router.use(bodyParser.urlencoded({ extended: true }));
  // router.set("trust proxy", true);
  // router.use(require('express').static('public')); // Use any middleware
  router.get("/ping", (req, res) => res.send("Guten Tag! " + new Date()));
  router.post(endpoint.handleWhatever , handleWhatever );
};


/** --- Initialize Express app by loading Probot --- */
probot.load(probotApp);

/* ############## Express instance ################ */
const app = probot.server;
const log = probot.log;
app.set("trust proxy", true);

/** --- Run Probot after setting everything up --- */
Probot.run(probotApp);

这里有一些 GitHub 问题和文档帮助我回答了我的问题: