React中如何将Promise封装的jQuery ajax请求改写为fetch?
问题修正说明
你写的转换版本无法生效,核心是混淆了jQuery ajax和原生fetch的配置差异,同时做了多余的逻辑包装,修正点如下:
- fetch原生返回Promise,无需额外手动包裹
new Promise构造,多余包裹且未调用resolve/reject会导致外层永远拿不到返回结果 - fetch没有jQuery ajax的
contentType/dataType/data配置项:- 请求头统一放在
headers配置对象中,JSON请求的Content-Type要在头里声明 - POST请求的提交数据放在
body字段,不是data字段 - fetch不会自动把响应解析为JSON,需要手动调用响应对象的
.json()方法完成解析,对应原dataType: 'json'的逻辑
- 请求头统一放在
- fetch仅在网络故障、请求未完成时触发reject,HTTP 4xx/5xx类的服务端错误需要手动通过
response.ok字段判断抛出 - 保持原逻辑:从解析后的响应数据中取出
configurations字段返回即可,不需要改动外层const self的对象结构。
最终可运行代码
async/await 写法(推荐,可读性更好)
const self = { fetchPreAuthnConfig: async (data) => { const response = await fetch(preAuthnEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }); // 拦截HTTP错误状态 if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } // 解析JSON响应,返回需要的configurations字段 const responseData = await response.json(); return responseData.configurations; } }; export default self;
Promise 链式写法(和原代码风格更接近)
const self = { fetchPreAuthnConfig: (data) => { return fetch(preAuthnEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(response => { if (!response.ok) { return Promise.reject(new Error(`请求失败,状态码:${response.status}`)); } return response.json(); }) .then(responseData => responseData.configurations); } }; export default self;
原错误写法的核心问题清单
- 外层多余包裹
new Promise,但内部fetch逻辑没有调用resolve/reject,导致Promise状态永远不会变更,外层拿不到结果 - 直接复用jQuery的配置字段,fetch无法识别
contentType/dataType/data,实际请求没有携带正确的请求头和提交参数 - 缺少响应JSON解析步骤,直接返回原始Response对象,拿不到实际业务数据
- 缺少HTTP错误状态判断,服务端返回4xx/5xx时不会进入错误分支
内容的提问来源于stack exchange,提问作者Genesis
相关产品推荐
相关产品推荐

