fetch请求总结,fastadmin中后台接口强制返回json数据

fetch请求

提交图片,只支持formData方式,这样会自动变为multiform方式,而且一般的post大多都可以用这样的方式来完成请求

javascript 复制代码
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('pid', id);
formData.append('dc', 1);

fetch('/api/common/upload', {
    method: 'POST',
    body: formData,
})
.then(response => response.json())
.then(data => {
    console.log('Success:', data);
})
.catch((error) => {
    console.error('Error:', error);
});

另外一种方式用json方式请求,大多数情况下,请求也都可以用这种方式

javascript 复制代码
                            fetch('/htgl.php/s/order/update_img?_ajax=1', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json', // 设置请求头为 JSON 格式
                                },
                                body: JSON.stringify({id: id, imgurl: data.data.fullurl}),
                            }).then(response => response.json())
                                .then(data => {
                                    console.log('Success:', data);
                                    $('#imgurl_src_' + id).attr('src', data.data.url);
                                    Toastr.success('更新图片成功');
                                })
                                .catch((error) => {
                                    Toastr.error(error || error.msg() || '请求失败,请检查网络');
                                    console.error('Error:', error);
                                }).finally(() => {
                                Layer.closeAll('loading');
                                Toastr.success('上传成功');
                            });

但是formData方式更灵活,不需要手动设置请求头,任何场景都适用,json则只支持一般数据,不支持文件和普通文本等特殊情况,建议使用formData方式

fastadmin中后台接口强制返回json数据只需要url后面跟上?_ajax=1即可

相关推荐
Ai runner10 小时前
Show call stack in perfetto from json input
java·前端·json
ID_1800790547311 小时前
淘宝商品详情API请求的全场景,带json数据参考
服务器·数据库·json
恒云客1 天前
python uv debug launch.json
数据库·python·json
wanderist.2 天前
从 TCP 到 JSON:一次 FastAPI + LLM 生产环境 “Unexpected end of JSON input” 的底层剖析
tcp/ip·json·fastapi
享誉霸王2 天前
15、告别混乱!Vue3复杂项目的规范搭建与基础库封装实战
前端·javascript·vue.js·前端框架·json·firefox·html5
今心上3 天前
关于json的理解测试!!
开发语言·json
强子感冒了3 天前
JSON和XML学习笔记
xml·学习·json
醒醒该学习了!4 天前
如何将json文件转成csv文件(python代码实操)
服务器·python·json
数据知道5 天前
JSON 与 BSON 深度解析:理解 MongoDB 底层数据格式与扩展类型。
数据库·mongodb·json
XLYcmy5 天前
智能体大赛 实现逻辑 大容量数据预处理机制
ai·llm·json·prompt·api·检索·万方数据库