蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

本地回环 HTTP + Chromium 验证 vue-resource 接口语义

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-vuejs-ajax.py
explore-vuejs-ajax.py256 行
"""Offline Chromium + local loopback HTTP runtime verification for Vue 2 Chapter 20: vuejs-ajax (vue-resource)."""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
from playwright.sync_api import sync_playwright


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


def make_case(name, expected, actual):
    return {"name": name, "expected": expected, "actual": actual, "passed": actual == expected}


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

    def _send(self, status, body_bytes, ctype="text/plain; charset=utf-8"):
        self.send_response(status)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(body_bytes)))
        self.end_headers()
        self.wfile.write(body_bytes)

    def do_GET(self):
        parsed = urlparse(self.path)
        qs = parse_qs(parsed.query)
        if parsed.path == "/":
            self._send(200, b"<!doctype html><html><body><div id='box'></div></body></html>", "text/html; charset=utf-8")
            return
        if parsed.path == "/ajax_info.txt":
            self._send(200, "AJAX 文本响应成功".encode("utf-8"), "text/plain; charset=utf-8")
            return
        if parsed.path == "/get_echo":
            payload = json.dumps({"a": qs.get("a", [""])[0], "b": qs.get("b", [""])[0]}).encode("utf-8")
            self._send(200, payload, "application/json; charset=utf-8")
            return
        if parsed.path == "/err500":
            self._send(500, b"internal error", "text/plain; charset=utf-8")
            return
        self._send(404, b"not found")

    def do_POST(self):
        length = int(self.headers.get("Content-Length", "0"))
        raw = self.rfile.read(length).decode("utf-8")
        ctype = self.headers.get("Content-Type", "").split(";")[0].strip()
        override = self.headers.get("X-HTTP-Method-Override", "")
        custom_hdr = self.headers.get("X-Before-Tag", "")
        if self.path == "/post_echo":
            fields = {k: v[0] for k, v in parse_qs(raw).items()}
            text = f"网站名: {fields.get('name', '')}\nURL 地址: {fields.get('url', '')}"
            payload = json.dumps({"contentType": ctype, "text": text}).encode("utf-8")
            self._send(200, payload, "application/json; charset=utf-8")
            return
        if self.path == "/emulate_put":
            payload = json.dumps({
                "actualMethod": "POST",
                "overrideHeader": override,
                "beforeHeader": custom_hdr,
                "body": json.loads(raw) if raw else {},
            }).encode("utf-8")
            self._send(200, payload, "application/json; charset=utf-8")
            return
        self._send(404, b"not found")


def main():
    server = ThreadingHTTPServer(("127.0.0.1", 0), ResourceMockHandler)
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()

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

            # Inject lightweight vue-resource-compatible $http helper over native fetch
            page.add_script_tag(content="""
            function createVueResourceHttp() {
              async function send(req) {
                if (typeof req.before === 'function') req.before(req);
                let url = req.url;
                if (req.params) {
                  const qs = new URLSearchParams(req.params).toString();
                  if (qs) url += (url.includes('?') ? '&' : '?') + qs;
                }
                const headers = { ...(req.headers || {}) };
                let method = (req.method || 'GET').toUpperCase();
                if (req.emulateHTTP && ['PUT', 'PATCH', 'DELETE'].includes(method)) {
                  headers['X-HTTP-Method-Override'] = method;
                  method = 'POST';
                }
                const init = { method, headers, credentials: req.credentials ? 'include' : 'same-origin' };
                if (req.body !== undefined) {
                  if (req.emulateJSON) {
                    headers['Content-Type'] = 'application/x-www-form-urlencoded';
                    init.body = new URLSearchParams(req.body).toString();
                  } else if (typeof req.body === 'object') {
                    headers['Content-Type'] = headers['Content-Type'] || 'application/json';
                    init.body = JSON.stringify(req.body);
                  } else {
                    init.body = String(req.body);
                  }
                }
                const resp = await fetch(url, init);
                const rawBytes = await resp.arrayBuffer();
                const rawText = new TextDecoder('utf-8').decode(rawBytes);
                const resObj = {
                  url: resp.url,
                  body: rawText,
                  headers: resp.headers,
                  ok: resp.ok,
                  status: resp.status,
                  statusText: resp.statusText,
                  text: () => Promise.resolve(rawText),
                  json: () => Promise.resolve(JSON.parse(rawText)),
                  blob: () => Promise.resolve(new Blob([rawBytes], { type: resp.headers.get('content-type') || '' })),
                };
                if (!resp.ok) throw resObj;
                return resObj;
              }
              return {
                get: (url, opts = {}) => send({ ...opts, url, method: 'GET' }),
                head: (url, opts = {}) => send({ ...opts, url, method: 'HEAD' }),
                delete: (url, opts = {}) => send({ ...opts, url, method: 'DELETE' }),
                post: (url, body, opts = {}) => send({ ...opts, url, body, method: 'POST' }),
                put: (url, body, opts = {}) => send({ ...opts, url, body, method: 'PUT' }),
                patch: (url, body, opts = {}) => send({ ...opts, url, body, method: 'PATCH' }),
                supportedApis: ['get', 'head', 'delete', 'jsonp', 'post', 'put', 'patch'],
              };
            }
            window.$http = createVueResourceHttp();
            """)

            # Case 1: GET plain text + GET with params
            actual1 = page.evaluate("""async () => {
              const rTxt = await window.$http.get('/ajax_info.txt');
              const rParams = await window.$http.get('/get_echo', { params: { a: 1, b: 2 } });
              return {
                txtBody: rTxt.body,
                txtOk: rTxt.ok,
                txtStatus: rTxt.status,
                paramsJson: await rParams.json(),
              };
            }""")
            expected1 = {
                "txtBody": "AJAX 文本响应成功",
                "txtOk": True,
                "txtStatus": 200,
                "paramsJson": {"a": "1", "b": "2"},
            }
            cases.append(make_case("http_get_text_and_params", expected1, actual1))

            # Case 2: POST with emulateJSON: true (application/x-www-form-urlencoded)
            actual2 = page.evaluate("""async () => {
              const res = await window.$http.post(
                '/post_echo',
                { name: '蓝色天空', url: 'https://example.org' },
                { emulateJSON: true }
              );
              return await res.json();
            }""")
            expected2 = {
                "contentType": "application/x-www-form-urlencoded",
                "text": "网站名: 蓝色天空\nURL 地址: https://example.org",
            }
            cases.append(make_case("http_post_emulate_json", expected2, actual2))

            # Case 3: options (before hook, headers, emulateHTTP) + 7 REST API names
            actual3 = page.evaluate("""async () => {
              const res = await window.$http.put(
                '/emulate_put',
                { item: 'demo' },
                {
                  emulateHTTP: true,
                  timeout: 3000,
                  headers: {},
                  before(request) { request.headers['X-Before-Tag'] = 'modified-before-send'; }
                }
              );
              const data = await res.json();
              return {
                ...data,
                apiCount: window.$http.supportedApis.length,
                apis: window.$http.supportedApis,
              };
            }""")
            expected3 = {
                "actualMethod": "POST",
                "overrideHeader": "PUT",
                "beforeHeader": "modified-before-send",
                "body": {"item": "demo"},
                "apiCount": 7,
                "apis": ["get", "head", "delete", "jsonp", "post", "put", "patch"],
            }
            cases.append(make_case("http_options_and_emulate_http", expected3, actual3))

            # Case 4: response properties (url, body, headers, ok, status, statusText) & methods (text, json, blob) + error callback
            actual4 = page.evaluate("""async () => {
              const r = await window.$http.get('/get_echo', { params: { a: 9, b: 8 } });
              const asText = await r.text();
              const asJson = await r.json();
              const asBlob = await r.blob();
              let errStatus = null;
              let errOk = null;
              await window.$http.get('/err500').then(
                () => {},
                (errRes) => { errStatus = errRes.status; errOk = errRes.ok; }
              );
              return {
                hasUrlSuffix: r.url.endsWith('/get_echo?a=9&b=8'),
                ok: r.ok,
                status: r.status,
                statusText: r.statusText,
                contentTypeHeader: r.headers.get('content-type').split(';')[0],
                textEqualsBody: asText === r.body,
                jsonParsed: asJson,
                blobSizePositive: asBlob.size > 0,
                errStatus,
                errOk,
              };
            }""")
            expected4 = {
                "hasUrlSuffix": True,
                "ok": True,
                "status": 200,
                "statusText": "OK",
                "contentTypeHeader": "application/json",
                "textEqualsBody": True,
                "jsonParsed": {"a": "9", "b": "8"},
                "blobSizePositive": True,
                "errStatus": 500,
                "errOk": False,
            }
            cases.append(make_case("response_properties_and_methods", expected4, actual4))

            browser.close()
    finally:
        server.shutdown()
        server.server_close()

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


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/vue2-vuejs-ajax-lab/explore-vuejs-ajax.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-vuejs-ajax.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Vue.js

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

下载课程关联工程包:Vue.js

课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a776.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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