跳至内容

WebApp

webapp 包可以让您的 Meteor 应用程序向 Web 浏览器提供内容。它包含在 meteor-base 包集中,当您运行 meteor create 时会自动添加。您可以轻松地构建一个没有它的 Meteor 应用程序 - 例如,如果您想创建一个仍然使用 Meteor 包系统和 DDP 的命令行工具。

此包还允许您为 HTTP 请求添加处理程序。这允许其他服务通过 HTTP API 访问您的应用程序数据,使其能够轻松地与尚不支持 DDP 的工具和框架互操作。

webapp 公开了 express API,用于通过 WebApp.handlers 处理请求。以下是一个允许您处理特定 URL 的示例

js
// Listen to incoming HTTP requests (can only be used on the server).
WebApp.handlers.use("/hello", (req, res, next) => {
  res.writeHead(200);
  res.end(`Hello world from: ${Meteor.release}`);
});

WebApp.handlers

仅限服务器

摘要

为所有 HTTP 请求注册处理程序。

参数

源代码
名称类型描述必需
path字符串

此处理程序仅在与该字符串匹配的路径上调用。匹配必须与 /. 相邻。

例如,/hello 将匹配 /hello/world/hello.world,但不匹配 /hello_world

handlerexpressHandlersCallback

将在 HTTP 请求上调用的处理程序函数。请参阅 expressHandlersCallback

js
import { WebApp } from "meteor/webapp";


const result = WebApp.handlers();
  "path",  // this param is optional 
ExpressHandlersCallback,
);

expressHandlersCallback(req, res, next)

仅限服务器

摘要

WebApp.expressHandlers 的回调处理程序

参数

源代码
名称类型描述必需
req对象

一个 Node.js IncomingMessage 对象,具有一些额外的属性。此参数可用于获取有关传入请求的信息。

res对象

一个 Node.js ServerResponse 对象。使用它来写入应作为对请求的响应发送的数据,并在完成时调用 res.end()

next函数

调用此函数将把此请求的处理传递给下一个相关的处理程序。

提供静态登录页面

使用 WebApp 可以做的非常酷的事情之一是为登录页面提供静态 HTML,在该页面上 TTFB(第一个字节时间)至关重要。

Bundle Visualizer动态导入 是帮助您最大程度地减少初始页面加载时间的绝佳工具。但有时您只需要将初始页面加载减少到最基本。

好消息是 WebApp 使这变得非常容易。

第一步是创建您的静态 HTML 文件并将其放置在应用程序根目录下的 private 文件夹中。

以下是一个您可以用来开始的示例 index.html

html
<head>
    <title>Fast Landing Page</title>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=no" />
    <link rel="stylesheet" href="path to your style sheet etc">
</head>

    <body>
        <!-- your content -->
    </body>

    <script>

    // any functions you need to support your landing page

    </script>

</html>
javascript
/* global WebApp Assets */
import crypto from "crypto";
import express from "express";

const router = express.Router();

router.get("/", async function (req, res, next) {
  const buf = await Assets.getTextAsync("index.html");

  if (buf.length > 0) {
    const eTag = crypto.createHash("md5").update(buf).digest("hex");

    if (req.headers["if-none-match"] === eTag) {
      res.writeHead(304, "Not Modified");
      return res.end();
    }

    res.writeHead(200, {
      ETag: eTag,
      "Content-Type": "text/html",
    });

    return res.end(buf);
  }

  return res.end("<html><body>Index page not found!</body></html>");
});

WebApp.handlers.use(router);

使用这种方法需要注意几件事。

我们使用 Assets 模块读取 index.html 的内容,该模块使从 private 根文件夹中读取文件变得非常容易。

我们使用 connect-route NPM 包来简化 WebApp 路由处理。但是您可以使用任何您想要的包来了解正在请求的内容。

最后,如果您决定使用此技术,您需要确保了解冲突的客户端路由将如何影响用户体验。

动态运行时配置

在某些情况下,能够控制在运行时初始化 Meteor 的 meteor_runtime_config 变量非常有价值。

示例

在某些情况下,单个 Meteor 服务器希望为多个 Cordova 应用程序提供服务,每个应用程序都有唯一的 ROOT_URL。但是有两个问题

  1. Meteor 服务器只能配置为服务单个 ROOT_URL
  2. cordova 应用程序在构建时配置了特定的 ROOT_URL

这两个条件会破坏 Cordova 应用程序的 autoupdate。如果服务器的 ROOT_URL 与 Cordova 应用程序的构建时配置的 ROOT_URL 不匹配,则 cordova-plugin-meteor-webapp 将失败更新。

为了解决此问题,webapp 提供了一个钩子,用于在服务器上动态配置 __meteor_runtime_config__

动态运行时配置钩子

js
WebApp.addRuntimeConfigHook(
  ({ arch, request, encodedCurrentConfig, updated }) => {
    // check the request to see if this is a request that requires
    // modifying the runtime configuration
    if (request.headers.domain === "calling.domain") {
      // make changes to the config for this domain
      // decode the current runtime config string into an object
      const config = WebApp.decodeRuntimeConfig(current);
      // make your changes
      config.newVar = "some value";
      config.oldVar = "new value";
      // encode the modified object to the runtime config string
      // and return it
      return WebApp.encodeRuntimeConfig(config);
    }
    // Not modifying other domains so return undefined
    return undefined;
  }
);

WebApp.addRuntimeConfigHook

仅限服务器

摘要

当 meteor 运行时配置 __meteor_runtime_config__ 发送到任何客户端时调用的钩子。

返回值: 对象 { stop: function, callback: function }

  • stop 函数 调用 stop() 以停止获取回调。
  • callback 函数 传入的 callback

参数

源代码
名称类型描述必需
callbackaddRuntimeConfigHookCallback

请参阅 addRuntimeConfigHookCallback 说明。

js
import { WebApp } from "meteor/webapp";

/** @returns Object */
const result = WebApp.addRuntimeConfigHook();
  addRuntimeConfigHookCallback
);

addRuntimeConfigHookCallback(options)

仅限服务器

摘要

addRuntimeConfigHook 的回调。

如果处理程序返回一个 假值,则钩子将不会修改运行时配置。

如果处理程序返回一个 字符串,则钩子将用该字符串替换编码的配置字符串。

警告: 钩子根本不检查返回值,调用者有责任使用辅助函数正确格式化。

addRuntimeConfigHookCallback 仅接受一个具有以下字段的 对象 参数

参数

源代码
名称类型描述必需
options对象
options.arch字符串

请求新运行时配置的客户端的体系结构。这可以是 web.browserweb.browser.legacyweb.cordova 之一。

options.request对象

一个 NodeJs IncomingMessage https://node.org.cn/api/http.html#http_class_http_incomingmessage 对象,可用于获取有关传入请求的信息。

options.encodedCurrentConfig字符串

当前配置对象编码为字符串,以便包含在根 html 中。

options.updated布尔值

如果自上次调用以来此体系结构的配置已更新,则为 true,否则为 false。此标志可用于缓存每个体系结构的解码/编码。

此外,还有两个辅助函数可用于解码运行时配置字符串和编码运行时配置对象。

WebApp.decodeRuntimeConfig

仅限服务器

摘要

接受编码的运行时字符串并返回运行时配置对象。

参数

源代码
名称类型描述必需
rtimeConfigString字符串----
js
import { WebApp } from "meteor/webapp";

/** @returns Object */
const result = WebApp.decodeRuntimeConfig();
  "rtimeConfigString"
);

WebApp.encodeRuntimeConfig

仅限服务器

摘要

接受运行时配置对象并返回编码的运行时字符串。

参数

源代码
名称类型描述必需
rtimeConfig对象----
js
import { WebApp } from "meteor/webapp";

/** @returns String */
const result = WebApp.encodeRuntimeConfig();
  rtimeConfig
);

更新的运行时配置钩子

js
const autoupdateCache;
// Get a notification when the runtime configuration is updated
// for each arch
WebApp.addUpdatedNotifyHook(({arch, manifest, runtimeConfig}) => {
  // Example, see if runtimeConfig.autoupdate has changed and if so
  // do something
  if(!_.isEqual(autoupdateCache, runtimeConfig.autoupdate)) {
    autoupdateCache = runtimeConfig.autoupdate;
    // do something...
  }
})

WebApp.addUpdatedNotifyHook

仅限服务器

摘要

更新 meteor 运行时配置时运行的钩子。通常,配置仅在开发模式下更改。

参数

源代码
名称类型描述必需
handleraddUpdatedNotifyHookCallback

handler 在每次更改 arch 运行时配置时都会被调用。请参阅 addUpdatedNotifyHookCallback

js
import { WebApp } from "meteor/webapp";

/** @returns Object */
const result = WebApp.addUpdatedNotifyHook();
  addUpdatedNotifyHookCallback
);

addUpdatedNotifyHookCallback(options)

仅限服务器

摘要

addupdatedNotifyHook 的回调处理程序

参数

源代码
名称类型描述必需
options对象
options.arch字符串

正在更新的体系结构。这可以是 web.browserweb.browser.legacyweb.cordova 之一。

options.manifest对象

arch 的新更新的清单对象。

options.runtimeConfig对象

arch 的新更新的配置对象。

main

仅限服务器

摘要

启动 HTTP 服务器。如果存在 UNIX_SOCKET_PATH,Meteor 的 HTTP 服务器将使用该套接字文件进行进程间通信,而不是 TCP。即使您选择不在应用程序中包含 webapp 包,也必须定义此方法才能使您的 Meteor 应用程序正常工作。