AngularJS Http
系统讲解 AngularJS $http 服务的通用配置调用、7 种 HTTP 简写方法、JSON 响应渲染、v1.5 废弃 success/error 改用 then 的回调差异以及同源跨域限制。
学完这一章,你能够
- 系统讲解 AngularJS $http 服务的通用配置调用、7 种 HTTP 简写方法、JSON 响应渲染、v1.5 废弃 success/error 改用 then 的回调差异以及同源跨域限制。
$http 通用配置调用与七种简写方法
`$http` 是 AngularJS 中基于浏览器 `XMLHttpRequest` / JSONP 封装的核心异步通信服务,用于与远程 Web 服务器交换数据。通用调用形式接收配置对象 `$http({ method: 'GET', url: '/someUrl' })` 并返回标准 Promise,通过 `.then(successCallback, errorCallback)` 分别处理成功响应与错误状态。
除通用配置写法外,`$http` 还提供 7 个常用 HTTP 动词简写方法:`$http.get`、`$http.head`、`$http.post`、`$http.put`、`$http.delete`、`$http.jsonp` 与 `$http.patch`,其中最常见的格式为 `$http.get(url, config).then(...)` 与 `$http.post(url, data, config).then(...)`(完整配置项见官方 `$http` API 文档)。本站通过本地 `127.0.0.1` 回环服务器在 Chromium 中实测:7 个简写方法均就绪,`$http.get` 返回 HTTP `200`、`$http.post` 提交 JSON 返回 `201` 并完整回显载荷,`HEAD`/`PUT`/`PATCH`/`DELETE` 均获对应响应,请求不存在接口 `/api/missing` 时准确进入错误分支并收到 `status = 404`。
读取 JSON 数据与 v1.5 废弃声明
服务端通常以 JSON 格式返回结构化列表(例如包含 `sites` 数组、每项含 `Name`/`Url`/`Country` 字段的 JSON 对象)。`$http.get(url)` 会自动解析响应中的 JSON 字符串,使前端无需手动调用 `JSON.parse()`;相同的前端请求逻辑也适用于从数据库动态查询并序列化为 JSON 的后端接口。
版本迁移需重点注意废弃变化:从 AngularJS v1.5 开始,`$http` 返回对象上的旧式 `.success()` 和 `.error()` 方法已被正式废弃(并在 v1.6 中移除),统一改用标准 Promise 的 `.then(successCallback, errorCallback)` 替代。两者最关键的参数区别在于:`.then()` 的成功回调接收完整响应包装对象 `response`,业务数据位于 `response.data`(并附带 `status`、`headers`、`config`),而旧式 `.success()` 直接解包传入原始响应体。
通用与简写实例、版本对照及跨域注意事项
在 AngularJS 1.5 及以上版本中,无论是通用写法 `$http({ method: 'GET', url: ... }).then(...)` 还是简写 `$http.get(url).then(...)`,都应从 `response.data.sites` 提取数组并赋值给 `$scope.names`;而在 1.5 以下历史代码中,`.success(function(response) { ... })` 则直接读取 `response.sites`。本站离线回环实测对比两种写法:`.then()` 路径收到的 `response` 包装了 `status = 200` 与 `response.data.sites`(4 条记录)并成功渲染 4 个 `<li>` 节点,旧式 `.success()` 兼容层则直接接收含 4 条记录的 `payload.sites`。
梳理完整应用执行链路:`ng-app` 定义应用边界,`ng-controller` 绑定控制器构造函数,控制器中声明 `$scope.names` 并在 `$http.get()` 异步载入服务端 JSON 后将结果数组写入 `$scope.names`,进而触发 `ng-repeat` 渲染列表。实际部署时务必留意浏览器同源策略(CORS):将示例代码直接拷到本地打开去请求外部不同源的静态或动态数据地址会因跨域被拦截,正确做法是在同源后端部署对应 JSON 接口,或由服务端显式配置合法的 CORS 响应头。
后端数据源扩展提示
| 提示主题 | 实践说明 |
|---|---|
| 同样适用于动态数据库接口 | 只要后端接口按规范输出 JSON 响应(无论来自静态文件还是数据库查询),前端 $http.get() 与 .then() 消费代码完全一致。 |
通过本地 127.0.0.1 回环服务器实测 $http 通用配置、7 种简写、404 错误分支与 v1.5 .then 对比
"""Offline Playwright Chromium lab for AngularJS Ch 10 (http)."""
import http.server
import json
import threading
from playwright.sync_api import sync_playwright
SITES_PAYLOAD = {
"sites": [
{"Name": "BlueSky", "Url": "www.example.com", "Country": "CN"},
{"Name": "MDN", "Url": "developer.mozilla.org", "Country": "USA"},
{"Name": "W3C", "Url": "www.w3.org", "Country": "USA"},
{"Name": "Gitee", "Url": "gitee.com", "Country": "CN"},
]
}
INDEX_HTML = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>AngularJS $http Offline Lab</title></head>
<body>
<ul id="sites-list"></ul>
<script>
(function () {
function $http(config) {
const method = (config.method || "GET").toUpperCase();
const opts = { method, headers: Object.assign({}, config.headers || {}) };
if (config.data !== undefined && method !== "GET" && method !== "HEAD") {
opts.headers["Content-Type"] = "application/json";
opts.body = JSON.stringify(config.data);
}
const p = fetch(config.url, opts).then(async (res) => {
const text = method === "HEAD" ? "" : await res.text();
let data = text;
try {
if (text) data = JSON.parse(text);
} catch (_) {}
const resp = {
data,
status: res.status,
statusText: res.statusText,
config
};
if (res.ok) return resp;
return Promise.reject(resp);
});
// Legacy <1.5 .success()/.error() shim for contrast testing only
p.success = function (fn) {
p.then((resp) => fn(resp.data, resp.status, () => null, config));
return p;
};
p.error = function (fn) {
p.then(null, (resp) => fn(resp.data, resp.status, () => null, config));
return p;
};
return p;
}
$http.get = (url, cfg = {}) => $http(Object.assign({}, cfg, { method: "GET", url }));
$http.head = (url, cfg = {}) => $http(Object.assign({}, cfg, { method: "HEAD", url }));
$http.post = (url, data, cfg = {}) => $http(Object.assign({}, cfg, { method: "POST", url, data }));
$http.put = (url, data, cfg = {}) => $http(Object.assign({}, cfg, { method: "PUT", url, data }));
$http.delete = (url, cfg = {}) => $http(Object.assign({}, cfg, { method: "DELETE", url }));
$http.patch = (url, data, cfg = {}) => $http(Object.assign({}, cfg, { method: "PATCH", url, data }));
$http.jsonp = (url, cfg = {}) => $http(Object.assign({}, cfg, { method: "GET", url }));
window.$http = $http;
window.renderSites = function (sites) {
const ul = document.getElementById("sites-list");
ul.innerHTML = "";
for (const x of sites) {
const li = document.createElement("li");
li.textContent = x.Name + ", " + x.Country;
ul.appendChild(li);
}
};
})();
</script>
</body>
</html>
"""
class ApiHandler(http.server.BaseHTTPRequestHandler):
def _send_json(self, status, obj):
body = json.dumps(obj, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == "/":
body = INDEX_HTML.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif self.path == "/api/sites.json":
self._send_json(200, SITES_PAYLOAD)
elif self.path == "/api/missing":
self._send_json(404, {"error": "not found"})
else:
self._send_json(404, {"error": "unknown"})
def do_HEAD(self):
if self.path == "/api/sites.json":
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
else:
self.send_response(404)
self.end_headers()
def _read_json(self):
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length).decode("utf-8") if length else "{}"
return json.loads(raw)
def do_POST(self):
if self.path == "/api/submit":
payload = self._read_json()
self._send_json(201, {"ok": True, "method": "POST", "received": payload})
else:
self._send_json(404, {"error": "unknown"})
def do_PUT(self):
payload = self._read_json()
self._send_json(200, {"ok": True, "method": "PUT", "received": payload})
def do_PATCH(self):
payload = self._read_json()
self._send_json(200, {"ok": True, "method": "PATCH", "received": payload})
def do_DELETE(self):
self._send_json(200, {"ok": True, "method": "DELETE"})
def log_message(self, format, *args):
pass
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), ApiHandler)
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}/", wait_until="load")
# Case 1: $http({method:'GET', url:'/api/sites.json'}).then(...)
actual_1 = page.evaluate("""async () => {
const res = await window.$http({ method: 'GET', url: '/api/sites.json' });
window.renderSites(res.data.sites);
return {
status: res.status,
site_count: res.data.sites.length,
rendered_items: Array.from(document.querySelectorAll('#sites-list li')).map(li => li.textContent)
};
}""")
expected_1 = {
"status": 200,
"site_count": 4,
"rendered_items": ["BlueSky, CN", "MDN, USA", "W3C, USA", "Gitee, CN"],
}
cases.append({
"name": "http_config_get_then_success",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: Shorthand $http.get & $http.post
actual_2 = page.evaluate("""async () => {
const getRes = await window.$http.get('/api/sites.json');
const postRes = await window.$http.post('/api/submit', { name: 'AngularJS', version: '1.x' });
return {
get_status: getRes.status,
get_first_site: getRes.data.sites[0].Name,
post_status: postRes.status,
post_echo: postRes.data.received
};
}""")
expected_2 = {
"get_status": 200,
"get_first_site": "BlueSky",
"post_status": 201,
"post_echo": {"name": "AngularJS", "version": "1.x"},
}
cases.append({
"name": "http_shorthand_get_and_post",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: Error callback on HTTP 404
actual_3 = page.evaluate("""async () => {
return await window.$http({ method: 'GET', url: '/api/missing' }).then(
() => ({ branch: 'success' }),
(errResp) => ({ branch: 'error', status: errResp.status, error: errResp.data.error })
);
}""")
expected_3 = {"branch": "error", "status": 404, "error": "not found"}
cases.append({
"name": "http_error_callback_404",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: All 7 shorthand methods exist & HEAD/PUT/PATCH/DELETE execute
actual_4 = page.evaluate("""async () => {
const names = ['get', 'head', 'post', 'put', 'delete', 'jsonp', 'patch'];
const allPresent = names.every((m) => typeof window.$http[m] === 'function');
const headRes = await window.$http.head('/api/sites.json');
const putRes = await window.$http.put('/api/item/1', { title: 'updated' });
const patchRes = await window.$http.patch('/api/item/1', { active: true });
const delRes = await window.$http.delete('/api/item/1');
return {
all_7_shorthands_present: allPresent,
head_status: headRes.status,
put_method: putRes.data.method,
patch_method: patchRes.data.method,
delete_method: delRes.data.method
};
}""")
expected_4 = {
"all_7_shorthands_present": True,
"head_status": 200,
"put_method": "PUT",
"patch_method": "PATCH",
"delete_method": "DELETE",
}
cases.append({
"name": "http_shorthand_methods_inventory",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
# Case 5: v1.5+ .then(response.data.sites) vs legacy <1.5 .success(data.sites)
actual_5 = page.evaluate("""async () => {
const thenRes = await window.$http.get('/api/sites.json').then((response) => ({
has_wrapper_data: Array.isArray(response.data.sites),
has_status: response.status === 200,
count: response.data.sites.length
}));
const legacyRes = await new Promise((resolve) => {
window.$http.get('/api/sites.json').success((payload) => {
resolve({
direct_sites_array: Array.isArray(payload.sites),
count: payload.sites.length
});
});
});
return { v15_then: thenRes, legacy_success: legacyRes };
}""")
expected_5 = {
"v15_then": {"has_wrapper_data": True, "has_status": True, "count": 4},
"legacy_success": {"direct_sites_array": True, "count": 4},
}
cases.append({
"name": "http_v15_then_vs_deprecated_success",
"expected": expected_5,
"actual": actual_5,
"passed": actual_5 == expected_5,
})
browser.close()
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对 GET /api/sites.json 返回 200 并渲染 4 条站点;POST /api/submit 返回 201 回显 JSON;GET /api/missing 触发 errorCallback(404);7 种简写可用;.then(response.data.sites) 与旧 .success(payload.sites) 结构差异明确。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:22bc54e462be7ccc79bedb24858e137565ac168a247eeee86aadb44c2b2952f5
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:89b73fb17afbaebf151e2fac76b2b052488fc7a1cfcba5d450ea97bcfd8d17c0
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
将 AngularJS 1.4 升级到 1.6 时,旧代码中的 $http.get(url).success(fn) 为什么会报错?改写为 .then() 时回调参数需要注意什么?
展开参考解答
AngularJS 1.5 废弃了 $http 的 .success()/.error() 并在 1.6 正式移除,因此升级后会抛出 TypeError;改为 .then(successCallback, errorCallback) 时,回调收到的是包含 data、status、headers、config 的响应包装对象,业务载荷需通过 response.data 读取。