技术 · 思考 · 实践 · 成长

首页/JavaScript/正文

JavaScript AJAX 与 Fetch:异步请求与跨域处理

JavaScript1 次阅读

前端拿数据靠 AJAX。本文讲 XHR 与 Fetch 两种方式、跨域与封装,结尾附请求封装小案例。

一、XMLHttpRequest(传统)

const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/user', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status >= 200 && xhr.status < 300) {
            console.log(JSON.parse(xhr.responseText));
        } else {
            console.error('失败', xhr.status);
        }
    }
};
xhr.send(JSON.stringify({ name: 'Tom' }));

二、Fetch(现代推荐)

const res = await fetch('/api/user', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'Tom' }),
    credentials: 'include',          // 带 cookie
});

if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();       // 解析 JSON(还有 res.text())
对比XHRFetch
语法回调Promise(配 async/await)
浏览器全兼容现代浏览器
4xx/5xx 错误status 判断不 reject(要自己查 res.ok)
默认带 cookie是需 credentials:include

三、GET 与查询参数

const params = new URLSearchParams({ page: 1, size: 10, kw: 'js' });
const res = await fetch(`/api/list?${params}`);    // 自动编码

// 读取响应头
res.headers.get('Content-Type');

四、文件上传(FormData)

const fd = new FormData();
fd.append('file', input.files[0]);
fd.append('type', 'avatar');
await fetch('/api/upload', { method: 'POST', body: fd });   // 不要设 Content-Type(浏览器自动带 boundary)

五、跨域(CORS)

同源 = 协议+域名+端口 全相同;不同源的 AJAX 会被浏览器拦截
解决:
1. 后端返回 CORS 头(Access-Control-Allow-Origin 等)—— 正解
2. 开发代理:devServer.proxy 把 /api 转发到后端(开发常用)
3. JSONP(仅 GET,老方案)
预检:带自定义头/PUT/DELETE 时浏览器先发 OPTIONS 询问
// Vite 开发代理示例(vite.config.js)
// server: { proxy: { '/api': 'http://localhost:8080' } }

六、注意

  • fetch 网络错误才 reject,HTTP 错误(404/500)正常 resolve —— 必须检查 res.ok;
  • fetch 无超时,要自己 AbortController 实现;
  • POST JSON 记得 stringify + 请求头;
  • 并发请求用 Promise.all。

七、小案例:API 请求封装

// request.js —— 带超时、错误统一处理、token 的请求封装
async function request(url, options = {}) {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), options.timeout ?? 10000);

    try {
        const res = await fetch(url, {
            ...options,
            headers: {
                'Content-Type': 'application/json',
                Authorization: localStorage.getItem('token')
                    ? `Bearer ${localStorage.getItem('token')}` : '',
                ...options.headers,
            },
            signal: controller.signal,
        });

        if (res.status === 401) { location.href = '/login'; return; }
        if (!res.ok) throw new Error(`HTTP ${res.status}`);

        return await res.json();
    } catch (err) {
        if (err.name === 'AbortError') throw new Error('请求超时');
        throw err;
    } finally {
        clearTimeout(timer);
    }
}

// 语法糖
const get  = (url, params) =>
    request(`${url}?${new URLSearchParams(params ?? {})}`);
const post = (url, data) =>
    request(url, { method: 'POST', body: JSON.stringify(data) });

// 使用
const users = await get('/api/users', { page: 1 });
await post('/api/users', { name: 'Tom' });

五件套:超时(AbortController)、token 头、401 跳登录、res.ok 校验、get/post 语法糖 —— 前端请求层的标准封装。

八、总结

Fetch 配 async/await 是主流;res.ok 必查、超时用 AbortController;FormData 上传不设头;跨域走后端 CORS 或开发代理;请求封装一次写好全局复用。

顺,不妄喜;逆,不惶馁;安,不奢逸;危,不惊惧。--史记

评论交流

0 条评论 · 支持多级回复
验证码
暂无评论,来说说你的想法吧

相关文章

继续阅读