蓝色天空网mbsky.com · 知识 · 实践 · 创造Vue.js · 本地阅读预览
教程 / 前端开发 / Vue.js

Vue.js Ajax(vue-resource)

核对历史库 vue-resource 的 GET/POST、emulateJSON/emulateHTTP、7 种 REST API、options 参数表与响应对象属性/方法表,并给出 Axios/Fetch 迁移建议。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

vue-resource 定位与已废弃迁移说明

早期 Vue 1.x 与部分 Vue 2.0 教程曾使用 `vue-resource` 插件(通过 CDN 引入 `vue-resource.min.js`)实现异步 HTTP 请求;但 Vue 官方早在 2.0 发布后即停止推荐 `vue-resource`(该库已归档/不再作为官方方案),新项目与存量迁移均应改用 `axios` 或浏览器原生 `Fetch API`。下文保留 `vue-resource` 的完整接口语义核对,便于维护历史项目代码。

GET 请求、POST emulateJSON 与 7 种 REST API

在 Vue 实例内可通过 `this.$http.get(url, [options]).then(successCallback, errorCallback)` 发起 GET 请求并读取 `res.body`;附加查询参数时使用 `{ params: { a: 1, b: 2 } }` 作为第二个参数。本站通过本地 `127.0.0.1` 回环服务 + Chromium 实测拉取 `/ajax_info.txt` 获得 `res.body = 'AJAX 文本响应成功'`(`ok = true`、`status = 200`),携带 `{ params: { a: 1, b: 2 } }` 请求 `/get_echo` 返回 `{ a: '1', b: '2' }`。

使用 `this.$http.post(url, body, options)` 向传统 PHP 等仅解析表单编码(`$_POST`)的后端提交数据时,需在第三个参数启用 `{ emulateJSON: true }`,将请求体编码从默认 `application/json` 转为 `application/x-www-form-urlencoded`。本站回环 Chromium 实测启用 `emulateJSON: true` 发送 `{ name: '蓝色天空', url: 'https://example.org' }`,服务端验证 `Content-Type` 为 `application/x-www-form-urlencoded` 并原样拼回预期两行文本。

`vue-resource` 支持全局 `Vue.http` 与实例 `this.$http` 两种调用入口,共提供 7 个 REST 风格方法:`get`、`head`、`delete`、`jsonp`、`post`、`put`、`patch`(除 `jsonp` 外其余 6 个对应标准 HTTP 方法)。下两张参考表完整核对请求 `options` 参数及响应对象属性与 Promise 解析方法;本站回环 Chromium 实测 `before(request)` 成功注入自定义请求头,`emulateHTTP: true` 将 `PUT` 转为 `POST` 并附带 `X-HTTP-Method-Override: PUT`,同时核验 `url`/`body`/`headers`/`ok`/`status`/`statusText` 及 `text()`/`json()`/`blob()` 方法,以及 HTTP 500 触发错误回调返回 `ok = false`、`status = 500`。

vue-resource options 请求参数参考

参数类型说明
urlstring请求的目标 URL 地址。
bodyObject, FormData, string作为 HTTP 请求体发送的数据载荷。
headersObject随请求发送的自定义 HTTP 请求头对象。
paramsObject序列化拼接到 URL 查询字符串的参数对象。
methodstringHTTP 请求方法名(如 GET、POST、PUT、DELETE 等)。
timeoutnumber请求超时时长(毫秒);`0` 表示不设置超时限制。
beforefunction(request)请求发出前用于修改请求对象或取消旧请求的钩子回调。
progressfunction(event)监听上传进度 `ProgressEvent` 的回调函数。
credentialsboolean跨站请求时是否携带 Cookie 等认证凭据。
emulateHTTPboolean设为 `true` 时以传统 `POST` 配合 `X-HTTP-Method-Override` 头模拟 `PUT`/`PATCH`/`DELETE`。
emulateJSONboolean设为 `true` 时将请求体以 `application/x-www-form-urlencoded` 表单格式发送。

vue-resource 响应对象属性与方法参考

属性/方法类型/返回值说明
urlstring响应对应的最终请求 URL。
bodyObject, Blob, string响应体原始或自动解析后的数据。
headersHeaders响应头集合对象(可通过 `get()` 读取指定头字段)。
okboolean当 HTTP 状态码处于 200–299 之间时为 `true`,否则为 `false`。
statusnumberHTTP 响应状态码(如 200、500)。
statusTextstringHTTP 状态原因短语(如 OK)。
方法(分组标识)Promise以下三项为响应体异步解析方法,均返回 Promise(原表作“约定值”)。
text()Promise<string>以 UTF-8 字符串形式异步解析并返回响应体。
json()Promise<Object>将响应体解析为 JSON 对象并异步返回。
blob()Promise<Blob>将响应体解析为二进制 `Blob` 对象并异步返回。

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

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 核对 GET 文本与 params、POST emulateJSON 表单编码、emulateHTTP 与 before 钩子,以及响应对象属性与 text/json/blob 方法。
本地回环 HTTP + Chromium 验证 vue-resource 接口语义

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

当前源码 SHA256:6a5c1b77f6bad4189967111296db83da49f5d9258d288fa0fef791af9e5b4e22

下载本站示例源码

本地运行

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

下载Vue.js Ajax(vue-resource)实验

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

ZIP SHA256:f425d458351308d5e80dbabe4228e2d7a590ed7f89a76da2255eadc9fd15da24

常见错误与边界

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

练习与解答

在历史 `vue-resource` 代码中,`emulateJSON: true` 与 `emulateHTTP: true` 分别解决什么服务端兼容问题?新项目应如何替代?

展开参考解答

`emulateJSON` 将请求体改为 `application/x-www-form-urlencoded` 以适配不支持 JSON 请求体的旧后端;`emulateHTTP` 通过 `POST` 加 `X-HTTP-Method-Override` 头绕过不支持 `PUT`/`PATCH`/`DELETE` 的服务器。新项目应改用 `axios` 或原生 `Fetch API`(配合 `URLSearchParams` 与自定义请求头)。

规范与官方依据