如何向Axios实例传递FormData以获取_boundary设置multipart请求头
解决方法
下面提供3种可落地的方案,优先推荐第一种:
方案1:删除手动配置的Content-Type,依赖axios自动处理(最优解)
axios本身对FormData类型的请求参数做了适配,当你调用post方法时第二个参数传入FormData实例,axios会自动生成正确的multipart/form-data请求头,自动填充对应的boundary值,完全不需要手动配置。
你只需要修改Services/index.js,移除headers中手动写的Content-Type配置即可:
//Services/index.js import axios from 'axios' import { Config } from '@/Config' const instance = axios.create({ baseURL: Config.API_URL, // 删掉手动写的Content-Type配置即可 timeout: 3000, }) // 其余原有代码保持不变
方案2:全局请求拦截器动态设置(适合多接口需要传FormData的场景)
如果你确实需要手动控制boundary的取值,可以通过添加请求拦截器,在每次请求发出前判断参数类型,动态读取FormData实例的_boundary属性设置到请求头:
//Services/index.js import axios from 'axios' import { Config } from '@/Config' const instance = axios.create({ baseURL: Config.API_URL, timeout: 3000, }) // 添加请求拦截器 instance.interceptors.request.use(config => { // 判断当前请求参数是FormData类型时,自动设置Content-Type if (config.data instanceof FormData) { config.headers['Content-Type'] = `multipart/form-data; boundary=${config.data._boundary}` } return config }) // 原有响应拦截器保持不变 instance.interceptors.response.use( response => response, ({ message, response: { data, status } }) => { return handleError({ message, data, status }) }, ) export default instance
方案3:调用接口时单独传入headers配置(适合仅少数接口用FormData的场景)
你也可以在loginService.js调用api.post时,通过第三个配置参数手动传入headers,直接读取当前方法拿到的form实例的_boundary:
//loginService.js import api from '@/Services' export default async form => { const response = await api.post('user/login/', form, { headers: { 'Content-Type': `multipart/form-data; boundary=${form._boundary}` } }) return response.data }
注意事项
_boundary是FormData实例的内部非标准属性,不同运行环境(浏览器/Node.js/不同框架的FormData polyfill)实现可能存在差异,非特殊需求不建议手动读取使用,优先用方案1的自动处理逻辑更稳妥。
内容的提问来源于stack exchange,提问作者ilvthsgm
相关产品推荐
相关产品推荐

