[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"$fU0GD0hU098lgDmr9gqeniP5P7NZ6L7ra0MRHpj95U0o":3},{"code":4,"message":5,"data":6},200,"成功",{"id":7,"createdAt":8,"title":9,"content":10,"summary":11,"image":12,"uid":13,"user":14,"categoryId":21,"category":22,"subCategoryId":24,"subCategory":25,"comments":27,"status":17,"reason":28,"notice":28,"visitCount":29,"commentCount":30,"keywords":31},21,"2024-01-26T13:49:03.139Z","如何在nuxt3中上传FormData文件","nuxt3中进行网络请求时，往往使用的是useFetch，当然其他使用方式如$fetch的。\n\n使用useFetch时，有和axios类似的网络interceptor，可以使用Promise在interceptor中自行决定返回某种格式的response，这里不赘述，只简单记一些可能出错的点。\n\n下面是一个简单的封装上传FormData的例子。\n\n```typescript\n// path example：/api/upload\nfunction upload\u003CT>(path: string, file: File) {\n  const formData = new FormData();\n  formData.append('file', file);\n  return useFetch\u003CT>(path, {\n    baseURL: 'https://www.xxxx.com', \n    key: path,\n    method: 'POST',\n    body: FormData,\n  })\n};\n```\n在这个例子中，将file文件挂载在名为“file”的formData中，然后传给useFetch的option中的body。\n\n服务端就可以通过post类型的该上传接口路由从MultipartForm中取出名为file的文件，然后进行上传处理，然后组装返回给客户端的response。\n\n有时候可能遇到的问题：no multipart boundary param in Content-Type\n如下截图：\n![报错截图](https://image.xinwei.ltd/11706276565695.png)\n\n这个问题目前我遇到的就是由于从Vue3的前端项目，重构为nuxt3项目时，老代码中的错误。\n\n错误的起因是在headers中多了一个内容类型Content-Type的声明（因为nuxt3在服务端渲染时，会自动添加含有boundary=的Content-Type）：\n```typescript\nreturn useFetch\u003CT>(path, {\n    baseURL: 'https://www.xxxx.com', \n    key: path,\n    method: 'POST',\n    body: FormData,\n    headers: { // 这里不要加Content-Type\n        \"Content-Type\": \"multiple/form-data\"  \n    }\n  })\n```\n截图为：\n![代码报错的地方截图](https://image.xinwei.ltd/21706276648780.png)\n\n对比一下在headers中添加Content-Type和不添加的效果对比：\n1. 添加Content-Type，如下图红框所示：\n![没有添加content-type的抓包](https://image.xinwei.ltd/31706276697489.png)\n\n2. 不添加Content-Type，nuxt3自动添加的是如下图所示：\n![](https://image.xinwei.ltd/41706276741721.png)\n\n从这2个对比的截图，我们可以看出，nuxt3在使用FormData类型的值给body字段时，会自动在Content-Type中加boundary信息。\n\n\n\n","在nuxt3中该如何使用网络请求API以FormData方式上传文件呢，这里会给大家提供演示的代码，以做参考。","https://image.xinwei.ltd/11706276565695.png",499668042977349,{"phone":15,"userId":13,"nickName":16,"vipType":17,"avatar":18,"sign":19,"createdAt":20},"13121171998","全栈老韩",1,"https://image.xinwei.ltd/images/IMG_5430.JPG","全栈工程师，擅长iOS App开发、前端（vue、react、nuxt、小程序&Taro）开发、Flutter、React Native、后端（midwayjs、golang、express、koa）开发、docker容器、seo优化等。","2024-01-01T16:14:30.305Z",2,{"id":21,"name":23},"IT技术",37,{"id":24,"name":26,"parentId":21},"全栈",[],"",1577,0,"nuxt,nuxt3,nuxt3 formdata,nuxt上传,nuxt知识,formdata"]