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即可

相关推荐
庖丁AI15 小时前
PDF 表格提取到 CSV 和 JSON 怎么做?复杂版式要先解决结构化解析
pdf·json
CedarQR1 天前
VS Code Copilot Chat 配置 MCP Server 全攻略(以 Next AI Draw.io 为例)
人工智能·ui·json
肖志-AI全栈1 天前
从零讲透 Ajax:XHR、Fetch、JSON 序列化到异步编程全链路
前端·ajax·json
前端Baymax2 天前
JSON配置文件的UTF-8 BOM编码陷阱
json
牢七2 天前
wordpress
okhttp
东方-教育技术博主4 天前
论文全文翻译_通过VR课堂适应性反馈提升职前教师注意能力
json·vr
Random_index4 天前
#Vue3篇: Vue 项目发版后如何提示用户刷新?基于 package.json 版本号的前端更新检测方案
前端·vue.js·json
寻道模式4 天前
【开发心得】GA + 飞书频繁报错被忽略的“元凶”
json·飞书·ga
SelectDB技术团队4 天前
Agent 场景动态 JSON 性能拆解:Apache Doris 比 ClickHouse 快 7 倍、比 Elasticsearch 快 2 倍
数据库·clickhouse·elasticsearch·json·apache·日志分析·apache doris
Dontla5 天前
Claude Code如何管理自动执行的命令?(/permissions命令、settings.json、settings.local.json、命令权限)
json