首页 > 解决方案 > 如何将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 错误,未找到。我在这里没有做什么?

标签: javascriptnode.jsaxiosfetch-api

解决方案


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));

推荐阅读