蓝色天空.知识 · 实践 · 创造
我的收藏
AngularJS 教程目录 26章
AngularJS / LEARN BY DOING

AngularJS 包含

核对 HTML 文件包含的服务端与客户端方案、ng-include 静态片段与 AngularJS 模板编译机制,以及 $sceDelegateProvider 白名单与 CORS 响应头的跨域实测。

学完这一章,你能够

  • 核对 HTML 文件包含的服务端与客户端方案、ng-include 静态片段与 AngularJS 模板编译机制,以及 $sceDelegateProvider 白名单与 CORS 响应头的跨域实测。

HTML 包含方案对比与 ng-include 基础

原生 HTML 本身并未内置直接包含外部 HTML 文件的标签语法。在传统 Web 开发中,通常借助服务端包含(SSI,Server Side Includes)在响应发出前完成拼接,例如在 PHP 中调用 `<?php require("navigation.php"); ?>` 将导航等公共片段合并到最终页面后再返回浏览器。

在客户端,JavaScript 常通过异步 HTTP 请求(AJAX)拉取片段并写入 `innerHTML`;而在 AngularJS 中,可直接使用 `ng-include` 指令加载外部 HTML 内容。需要注意 `ng-include` 的属性值会被当作 AngularJS 表达式求值,因此直接书写文件路径时必须在双引号内再套单引号,如 `<div ng-include="'partial.htm'"></div>`。本站离线 Chromium 环回服务实测:字面量路径 `'partial.htm'` 与作用域变量 `dynamicPath` 均成功载入片段并渲染出标题“示例局部片段”及正文段落。

在被包含文件中执行 AngularJS 模板代码

`ng-include` 不仅能插入纯静态 HTML,还会把载入的模板交给 AngularJS 编译器处理,因此片段内部的 `ng-repeat` 与插值表达式均可继承当前作用域数据正常求值。例如控制器通过 `$http.get` 拉取后端接口(如 `sites.php` 或 JSON 接口)返回的 `records` 列表并挂到 `$scope.names`,而外部模板文件 `sites.htm` 内编写 `<tr ng-repeat="x in names"><td>{{ x.Name }}</td><td>{{ x.Url }}</td></tr>` 即可渲染表格(注:负责承载 AngularJS 模板指令的是 `sites.htm`,后端脚本负责提供 JSON 数据)。本站实测载入 3 条记录(Alpha、Beta、Gamma),表格准确渲染 `3` 行名称与链接单元格。

跨域包含:$sceDelegateProvider 白名单与 CORS 响应头

出于安全策略,AngularJS 的 `$sce`(Strict Contextual Escaping)默认仅允许 `ng-include` 请求同源(`'self'`)模板,直接填写跨源地址会被拦截。若需包含其他域名的片段,必须在模块 `.config` 阶段注入 `$sceDelegateProvider` 并调用 `resourceUrlWhitelist([...])`(AngularJS 1.8.x 推荐新别名 `trustedResourceUrlList`)登记允许的通配地址,同时建议保留 `'self'` 以免阻断站内同源模板。

仅在前端配置白名单并不足以完成跨域拉取,目标服务端还必须返回允许跨域的 CORS 响应头(例如 PHP 中输出 `header('Access-Control-Allow-Origin:*');` 或指定可信来源)。本站在 Chromium 中启动双端口环回服务对比验证:未加白名单时跨源包含直接返回 `sce:insecurl`;加入白名单且服务端携带 `Access-Control-Allow-Origin: *` 时成功渲染红色片段“我是跨域的内容”(计算色值 `rgb(255, 0, 0)`);而即使已加入前端白名单,若服务端缺失该 CORS 响应头,浏览器仍会拦截请求并保持目标容器为空。

离线 Chromium 双端口服务实测 ng-include 模板编译与 CORS 白名单

含完整源码 · 313 行
展开查看收起
python
"""Offline Playwright Chromium lab for AngularJS Ch 21: include (ng-include & CORS whitelist)."""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from playwright.sync_api import sync_playwright


class _PrimaryHandler(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        return

    def _send(self, body: str, content_type: str = "text/html; charset=utf-8"):
        data = body.encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if self.path == "/partial.htm":
            self._send("<h1>示例局部片段</h1><p>这是一个通过 ng-include 动态载入的 HTML 片段。</p>")
        elif self.path == "/sites.htm":
            self._send(
                '<table id="sites-tbl">'
                '<tr ng-repeat="x in names"><td>{{ x.Name }}</td><td>{{ x.Url }}</td></tr>'
                "</table>"
            )
        elif self.path == "/sites.json":
            payload = json.dumps(
                {
                    "records": [
                        {"Name": "Alpha", "Url": "https://alpha.example"},
                        {"Name": "Beta", "Url": "https://beta.example"},
                        {"Name": "Gamma", "Url": "https://gamma.example"},
                    ]
                },
                ensure_ascii=False,
            )
            self._send(payload, "application/json; charset=utf-8")
        elif self.path == "/":
            self._send(MAIN_HTML)
        else:
            self.send_error(404)


class _CrossOriginHandler(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        return

    def do_GET(self):
        if self.path == "/cors/allowed.htm":
            data = '<b id="cors-msg" style="color:red">我是跨域的内容</b>'.encode("utf-8")
            self.send_response(200)
            self.send_header("Access-Control-Allow-Origin", "*")
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)
        elif self.path == "/cors/blocked.htm":
            data = "<b>缺少 CORS 响应头的跨域内容</b>".encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            self.wfile.write(data)
        else:
            self.send_error(404)


MAIN_HTML = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>AngularJS ng-include 离线实验</title></head>
<body>
  <div id="slot-static" ng-include="'/partial.htm'"></div>
  <div id="slot-var" ng-include="dynamicPath"></div>
  <div id="slot-sites" ng-include="'/sites.htm'"></div>
  <div id="slot-cors-default"></div>
  <div id="slot-cors-allowed"></div>
  <div id="slot-cors-no-header"></div>
  <script>
    // Offline AngularJS 1.x ng-include + $sceDelegateProvider + $http + ng-repeat equivalence runtime
    function createSceDelegate() {
      let whitelist = ['self'];
      function patternToRegex(pattern) {
        const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');
        return new RegExp('^' + escaped.replace(/\\*\\*/g, '.*').replace(/\\*/g, '[^/]*') + '$');
      }
      return {
        resourceUrlWhitelist(list) {
          if (Array.isArray(list)) whitelist = list.slice();
          return whitelist;
        },
        isTrusted(url) {
          const resolved = new URL(url, window.location.href);
          if (whitelist.includes('self') && resolved.origin === window.location.origin) {
            return true;
          }
          return whitelist.some((pat) => pat !== 'self' && patternToRegex(pat).test(resolved.href));
        }
      };
    }

    function evalExpr(expr, scope) {
      const trimmed = expr.trim();
      if ((trimmed.startsWith("'") && trimmed.endsWith("'")) || (trimmed.startsWith('"') && trimmed.endsWith('"'))) {
        return trimmed.slice(1, -1);
      }
      return trimmed.split('.').reduce((acc, k) => (acc == null ? undefined : acc[k]), scope);
    }

    function compileNgRepeat(root, scope) {
      const nodes = Array.from(root.querySelectorAll('[ng-repeat]'));
      for (const tpl of nodes) {
        const spec = tpl.getAttribute('ng-repeat');
        const m = /^(\\w+)\\s+in\\s+([\\w.]+)$/.exec(spec.trim());
        if (!m) continue;
        const [, itemVar, listExpr] = m;
        const items = evalExpr(listExpr, scope) || [];
        const parent = tpl.parentNode;
        const htmlTpl = tpl.outerHTML.replace(/\\s*ng-repeat="[^"]*"/, '');
        tpl.remove();
        for (const item of items) {
          const childScope = Object.assign({}, scope, { [itemVar]: item });
          const rendered = htmlTpl.replace(/\\{\\{\\s*([^}]+?)\\s*\\}\\}/g, (_, ex) => {
            const val = evalExpr(ex, childScope);
            return val == null ? '' : String(val);
          });
          parent.insertAdjacentHTML('beforeend', rendered);
        }
      }
    }

    async function runNgInclude(el, expr, scope, sce) {
      const url = evalExpr(expr, scope);
      if (!url) return { ok: false, error: 'empty_url' };
      if (!sce.isTrusted(url)) {
        return { ok: false, error: 'sce:insecurl' };
      }
      try {
        const resp = await fetch(url);
        if (!resp.ok) return { ok: false, error: 'http_' + resp.status };
        const html = await resp.text();
        el.innerHTML = html;
        compileNgRepeat(el, scope);
        return { ok: true, status: resp.status };
      } catch (err) {
        return { ok: false, error: 'cors_or_network_error' };
      }
    }

    window.__lab = { createSceDelegate, runNgInclude };
  </script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    srv_a = ThreadingHTTPServer(("127.0.0.1", 0), _PrimaryHandler)
    srv_b = ThreadingHTTPServer(("127.0.0.1", 0), _CrossOriginHandler)
    port_a = srv_a.server_address[1]
    port_b = srv_b.server_address[1]
    t_a = threading.Thread(target=srv_a.serve_forever, daemon=True)
    t_b = threading.Thread(target=srv_b.serve_forever, daemon=True)
    t_a.start()
    t_b.start()

    cases = []
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            try:
                page = browser.new_page()
                page.goto(f"http://127.0.0.1:{port_a}/", wait_until="load")

                # Case 1: Same-origin static include (literal string vs scope expression)
                res1 = page.evaluate("""async () => {
                    const sce = window.__lab.createSceDelegate();
                    const elStatic = document.getElementById('slot-static');
                    const r1 = await window.__lab.runNgInclude(elStatic, elStatic.getAttribute('ng-include'), {}, sce);
                    const elVar = document.getElementById('slot-var');
                    const r2 = await window.__lab.runNgInclude(elVar, elVar.getAttribute('ng-include'), { dynamicPath: '/partial.htm' }, sce);
                    return {
                        literal_ok: r1.ok,
                        h1: elStatic.querySelector('h1')?.textContent || '',
                        p: elStatic.querySelector('p')?.textContent || '',
                        var_ok: r2.ok,
                        var_h1: elVar.querySelector('h1')?.textContent || ''
                    };
                }""")
                exp1 = {
                    "literal_ok": True,
                    "h1": "示例局部片段",
                    "p": "这是一个通过 ng-include 动态载入的 HTML 片段。",
                    "var_ok": True,
                    "var_h1": "示例局部片段",
                }
                cases.append(dict(
                    name="same_origin_static_include",
                    expected=exp1,
                    actual=res1,
                    passed=(res1 == exp1),
                ))

                # Case 2: Included AngularJS template with $http.get JSON + ng-repeat compilation
                res2 = page.evaluate("""async () => {
                    const sce = window.__lab.createSceDelegate();
                    const dataResp = await fetch('/sites.json');
                    const data = await dataResp.json();
                    const scope = { names: data.records };
                    const el = document.getElementById('slot-sites');
                    const r = await window.__lab.runNgInclude(el, el.getAttribute('ng-include'), scope, sce);
                    const rows = Array.from(el.querySelectorAll('#sites-tbl tr')).map(tr =>
                        Array.from(tr.querySelectorAll('td')).map(td => td.textContent)
                    );
                    return { ok: r.ok, row_count: rows.length, rows };
                }""")
                exp2 = {
                    "ok": True,
                    "row_count": 3,
                    "rows": [
                        ["Alpha", "https://alpha.example"],
                        ["Beta", "https://beta.example"],
                        ["Gamma", "https://gamma.example"],
                    ],
                }
                cases.append(dict(
                    name="included_template_with_ng_repeat_and_http",
                    expected=exp2,
                    actual=res2,
                    passed=(res2 == exp2),
                ))

                # Case 3: Cross-origin blocked by default $sce, then allowed via resourceUrlWhitelist + CORS header
                res3 = page.evaluate(f"""async () => {{
                    const crossUrl = 'http://127.0.0.1:{port_b}/cors/allowed.htm';
                    const sceDefault = window.__lab.createSceDelegate();
                    const elDef = document.getElementById('slot-cors-default');
                    const blocked = await window.__lab.runNgInclude(elDef, "'" + crossUrl + "'", {{}}, sceDefault);

                    const sceAllowed = window.__lab.createSceDelegate();
                    sceAllowed.resourceUrlWhitelist(['self', 'http://127.0.0.1:{port_b}/cors/**']);
                    const elOk = document.getElementById('slot-cors-allowed');
                    const allowed = await window.__lab.runNgInclude(elOk, "'" + crossUrl + "'", {{}}, sceAllowed);
                    const msgEl = elOk.querySelector('#cors-msg');
                    return {{
                        default_blocked_error: blocked.error,
                        whitelisted_ok: allowed.ok,
                        text: msgEl ? msgEl.textContent : '',
                        color: msgEl ? getComputedStyle(msgEl).color : ''
                    }};
                }}""")
                exp3 = {
                    "default_blocked_error": "sce:insecurl",
                    "whitelisted_ok": True,
                    "text": "我是跨域的内容",
                    "color": "rgb(255, 0, 0)",
                }
                cases.append(dict(
                    name="cross_origin_sce_whitelist_enforcement",
                    expected=exp3,
                    actual=res3,
                    passed=(res3 == exp3),
                ))

                # Case 4: Whitelisted in $sce but server omits Access-Control-Allow-Origin -> browser blocks CORS
                res4 = page.evaluate(f"""async () => {{
                    const crossBlockedUrl = 'http://127.0.0.1:{port_b}/cors/blocked.htm';
                    const sce = window.__lab.createSceDelegate();
                    sce.resourceUrlWhitelist(['self', 'http://127.0.0.1:{port_b}/cors/**']);
                    const el = document.getElementById('slot-cors-no-header');
                    const r = await window.__lab.runNgInclude(el, "'" + crossBlockedUrl + "'", {{}}, sce);
                    return {{
                        sce_trusted: sce.isTrusted(crossBlockedUrl),
                        fetch_ok: r.ok,
                        error: r.error,
                        slot_html: el.innerHTML
                    }};
                }}""")
                exp4 = {
                    "sce_trusted": True,
                    "fetch_ok": False,
                    "error": "cors_or_network_error",
                    "slot_html": "",
                }
                cases.append(dict(
                    name="cross_origin_missing_cors_header_blocked",
                    expected=exp4,
                    actual=res4,
                    passed=(res4 == exp4),
                ))
            finally:
                browser.close()
    finally:
        srv_a.shutdown()
        srv_b.shutdown()
        srv_a.server_close()
        srv_b.server_close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对同源静态片段加载、$http JSON 与 ng-repeat 模板 3 行渲染、默认 $sce 拦截 sce:insecurl、白名单+CORS 成功渲染及缺省 CORS 头被浏览器拦截。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a851.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:AngularJS

课程关联工程包(登记关联26章) · 含当前章节或实例 · mbskycom202612a851.zip

下载课程关联工程包:AngularJS

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a863.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

ng-include 会把属性值作为 AngularJS 表达式求值,外层双引号供 HTML 解析,内层单引号才能表示字符串字面量路径;跨域包含必须同时满足前端通过 $sceDelegateProvider.resourceUrlWhitelist(1.8+ 为 trustedResourceUrlList)放行目标 URL,以及服务端返回匹配的 Access-Control-Allow-Origin 响应头。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习