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

相关推荐
njsgcs7 小时前
json转excel python pd
python·json·excel·pd
代码搬运媛17 小时前
【架构相关】tsconfig.json 与 tsconfig.node.json、tsconfig.app.json 的关系和作用
node.js·json
Jeled18 小时前
Android 网络层最佳实践:Retrofit + OkHttp 封装与实战
android·okhttp·kotlin·android studio·retrofit
aerror2 天前
json转excel xlsx文件
开发语言·python·json
掉鱼的猫2 天前
全球首个支持 IETF JSONPath (RFC 9535) 标准的 Java 框架,Snack4-Jsonpath v4.0.0 发布
java·json
吹个口哨写代码3 天前
处理文本编辑器存的json格式报错问题,对编辑器存的字段进行转换处理,再通过json返回
java·编辑器·json
APIshop3 天前
代码实例:Python 爬虫抓取与解析 JSON 数据
爬虫·python·json
得物技术3 天前
从 JSON 字符串到 Java 对象:Fastjson 1.2.83 全程解析|得物技术
java·后端·json
allk554 天前
OkHttp源码解析(一)
android·okhttp
allk554 天前
OkHttp源码解析(二)
android·okhttp