发送 GET 请求的方式汇总
1. 浏览器直接访问 URL
直接在地址栏输入 URL 回车 → 就是一个 GET 请求
2. HTML 标签(被动触发)
<!-- link 标签 -->
<link rel="stylesheet" href="https://api.example.com/style.css" />
<!-- script 标签 -->
<script src="https://api.example.com/data.js"></script>
<!-- img 标签 -->
<img src="https://api.example.com/image?id=1" />
<!-- a 标签点击跳转 -->
<a href="https://api.example.com/page">跳转</a>
<!-- form 表单(默认 method 就是 GET) -->
<form action="https://api.example.com/search" method="get">
<input name="keyword" />
<button type="submit">搜索</button>
</form>
3. XMLHttpRequest(Ajax 传统方式)
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/users?id=1');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();
4. Fetch API(现代原生方式)
// 默认就是 GET 请求
const res = await fetch('https://api.example.com/users?id=1');
const data = await res.json();
console.log(data);
5. Axios
// 方式一
axios.get('https://api.example.com/users', {
params: { id: 1 }
});
// 方式二
axios({
method: 'get',
url: 'https://api.example.com/users',
params: { id: 1 }
});
6. Node.js 环境
// 原生 https 模块
import https from 'https';
https.get('https://api.example.com/users?id=1', (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => console.log(JSON.parse(data)));
});
// 使用 node-fetch / axios(同浏览器用法)
const res = await fetch('https://api.example.com/users?id=1');
总结对比
| 方式 | 场景 | 是否跨域受限 |
|---|---|---|
| 浏览器地址栏 | 页面跳转 | ❌ 不受限 |
<img>/<script>/<link> | 资源加载 | ❌ 不受限(JSONP利用此点) |
<form method="get"> | 表单提交 | ❌ 不受限 |
| XHR / Fetch | Ajax 异步请求 | ✅ 受 CORS 限制 |
| Axios | Ajax 封装库 | ✅ 受 CORS 限制 |
| curl / Node.js | 服务端请求 | ❌ 无跨域概念 |
面试加分点:
<script>标签不受跨域限制这一特性,正是 JSONP 的实现原理。