javascript - 如何将axios转换为fetch?
问题描述
我熟悉使用 Axios 发布数据,但尝试使用 fetch 代替。我将如何转换为获取请求,我认为我所做的是正确的......
const data = new FormData();
以下 axios 请求有效:
data.append( 'Image', this.state.image, this.state.image.name );
axios.post( '/api/upload', data, {
headers: {
'accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.8',
'Content-Type': 'multipart/form-data;',
}
})
.then ...
我试图在这里转换;
data.append( 'Image', this.state.image, this.state.image.name );
fetch( '/api/upload', data, {
method: 'POST',
headers: {
'accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.8',
'Content-Type': 'multipart/form-data;',
},
body: JSON.stringify(data)
})
.then ...
返回 404 错误,未找到。我在这里没有做什么?
解决方案
fetch
只需要两个参数。
fetch('/api/upload', {
method: 'post',
body: JSON.stringify(data),
headers: {
'accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.8',
'Content-Type': 'multipart/form-data;',
},
})
.then(res => res.json())
.then(json => console.log(json));
推荐阅读
- excel - Graph API in Excel for Office 365
- javascript - 具有动态创建元素的 Javascript 操作顺序
- java - 绑定地图
> HTML 文本框中的实例 - android - 如何将 google vr sdk 导入我的 Android Studio 项目
- android - 设备如何在使用相机时截取屏幕截图?我们无法捕获表面视图
- python - 使用 CreateChatRequest 发生用户不足(例如创建聊天)
- python - Extract features into a dataset from keras model
- jenkins-x - 为 Jenkins X 更新构建 podTemplate
- django - What are naming rules of templates in django class based views
- javascript - npm test 很好,但它也会在 askBackend ReferenceError: localStorage is not defined 处引发未捕获的错误