---
# System prepended metadata

title: axios formdata 可能遇到問題
tags: [javascript, nuxt]

---

# Formdata & Axios 筆記

### 用法
```javascript
const formData = new FormData();
formData.append("file", file);
```
#### fetch API
```javascript
const callAPI = async (data) => {
    const result = await fetchURL(`API url`, {
      method: "POST",
      body: data,
    });
    return result;
};
```
#### server端
```javascript
import FormData from "form-data";
import axios from "@/utils/axios";
export default defineEventHandler(async (event) => {
  try {
    const body = await readMultipartFormData(event);
    const formData = new FormData();
    formData.append(body[0].name, body[0].data);
    formData.append(body[1].name, body[1].data, body[1].filename, body[1].type); // file
    const headersList = {
      ...formData.getHeaders(),
    };
    const bodyContent = formData;
    const reqOptions = {
      url: `API url`,
      method: "POST",
      data: bodyContent,
      headers: headersList,
    };
    const response = await axios.request(reqOptions);
    return response.data;
  } catch (e) {
    return { status: e.response.status, message: e.response.data.message };
  }
});

```

### Request body larger than maxBodyLength limit
[參考這篇](https://segmentfault.com/a/1190000040050549)
axios 的 request body 有默認的長度上限，所以當使用 formdata 
上傳檔案過大時，會發生這個錯誤

#### 解決方法
在 headers 加上這個，將 body 長度設為無限，即可避免這個錯誤。
```javascript
maxBodyLength: Infinity
```

### formdata 無法 getHeaders()
[參考這篇](https://stackoverflow.com/questions/54682225/form-data-axios-unable-to-get-headers-from-formdata-error-getheaders-is-not/54685950#54685950)
在瀏覽器調用會使用 windows 原生的 formdata，會不包含getHeaders()。

#### 解決方法
引用 Node 的 form-data
```javascript
import FormData from "form-data";
```