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

相关推荐
wtsolutions12 分钟前
Using the JSON to Excel API - Programmatic Access for Developers
json·excel
wtsolutions3 小时前
Understanding JSON Formats - What JSON to Excel Supports
json·excel
wtsolutions4 小时前
Advanced Features - Unlocking the Power of JSON to Excel Pro
linux·json·excel
wtsolutions7 小时前
Real-World Use Cases - How Organizations Use JSON to Excel
json·excel
wtsolutions7 小时前
Introduction to JSON to Excel - The Ultimate Conversion Tool
json·excel
San30.8 小时前
LangChain 第二课:拒绝“废话”,用 Zod 强制 AI 输出标准 JSON
人工智能·langchain·json
wtsolutions8 小时前
JSON to Excel WPS Add-in - Perfect for WPS Office Users
json·excel·wps
wtsolutions9 小时前
Flat vs Nested JSON Conversion - Deep Dive into Conversion Modes
json
岁岁种桃花儿9 小时前
XMLHttpRequest 从入门到实战:GET/POST 请求完整案例
ajax·okhttp
weixin_462446239 小时前
【实战】Java使用 Jsoup 将浏览器书签 HTML 转换为 JSON(支持多级目录)
java·html·json·书签