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

相关推荐
wtsolutions6 小时前
Excel-to-JSON插件专业版功能详解:让Excel数据转换更灵活
json·excel·excel-to-json·wtsolutions·专业版
kerryYG7 小时前
使用JMETER中的JSON提取器实现接口关联
jmeter·json
xzkyd outpaper7 小时前
okhttp原理
okhttp
柯ran1 天前
JSON|cJSON 介绍以及具体项目编写
c语言·链表·json·github
酷小洋2 天前
Ajax基础
前端·ajax·okhttp
乐言3612 天前
Jmeter中的Json提取器如何使用?
jmeter·json
北海有初拥2 天前
【从零实现JsonRpc框架#1】Json库介绍
json
GalenWu3 天前
对象转换为 JSON 字符串(或反向解析)
前端·javascript·微信小程序·json
致于数据科学家的小陈3 天前
Go 层级菜单树转 json 处理
python·go·json·菜单树·菜单权限·children
我爱夜来香A3 天前
SQL进阶:如何把字段中的键值对转为JSON格式?
数据库·sql·json