axios配合formidable上传文件报错Data after transformation must be合法类型求助
问题原因排查
- axios调用语法错误:
axios.post()的合法入参格式为axios.post(请求URL, 提交数据, 配置项),你直接把配置对象作为第一个参数传入,第二个参数传了formidable的解析回调函数,完全不符合API要求,导致axios无法识别要提交的数据,直接触发转换错误。 - formidable未实际解析请求数据:你仅实例化了formidable对象,没有调用
form.parse(req)去解析当前进来的上传请求,没有拿到上传的文件/表单字段数据。 - 请求头配置错误:上传文件需要使用
multipart/form-data格式的请求头,你配置的application/json完全不支持二进制文件传输。 - 请求处理逻辑混乱:没有区分静态资源请求和上传接口请求,所有请求都会同时触发axios上传、静态文件读取两个异步逻辑,会出现重复响应的问题。
可行解决方案
首先安装缺失依赖:npm install axios formidable form-data,其中form-data用来构造符合要求的上传表单数据。
修正后的完整代码:
const http = require('http'); const fs = require('fs'); const path = require('path'); const axios = require('axios'); const formidable = require('formidable'); const FormData = require('form-data'); var mimeType = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword', '.eot': 'application/vnd.ms-fontobject', '.ttf': 'application/font-sfnt' }; const postUrl = "https://example.com/345678934/attachments"; var server = http.createServer(function(req, response) { // 区分上传接口和静态资源请求 if (req.method.toLowerCase() === 'post' && req.url === '/upload') { // 处理上传逻辑 const form = formidable({ multiples: true, keepExtensions: true }); form.parse(req, async function(err, fields, files) { if (err) { response.writeHead(500, {'content-type': 'application/json'}); return response.end(JSON.stringify({error: '表单解析失败'})); } try { // 构造FormData const formData = new FormData(); // 添加上传的所有文件,兼容单/多文件 const fileList = Array.isArray(files.file) ? files.file : [files.file]; fileList.forEach(file => { formData.append('file', fs.createReadStream(file.filepath), { filename: file.originalFilename, contentType: file.mimetype }); }); // 添加其他表单字段 Object.keys(fields).forEach(key => { formData.append(key, fields[key]); }); // 调用axios上传 const uploadRes = await axios.post(postUrl, formData, { headers: formData.getHeaders() }); response.writeHead(200, {'content-type': 'application/json'}); response.end(JSON.stringify({ code: 0, msg: '上传成功', data: uploadRes.data })); console.log("Upload completed"); } catch (error) { console.error("上传错误", error); response.writeHead(500, {'content-type': 'application/json'}); response.end(JSON.stringify({error: '上传失败', detail: error.message})); } }); return; } // 静态资源返回逻辑 var filePath = '.' + req.url; if (filePath == './') { filePath += "templates/index.html" } if (filePath == './success') { filePath = "templates/success.html" } fs.readFile(filePath, function(error, content) { if (error) { if (error.code == 'ENOENT') { response.writeHead(404); response.end('Page not Found'); } else { response.writeHead(500); response.end('Internal error: ' + error.code); } } else { var extname = path.extname(filePath); response.writeHead(200, { 'Content-Type': mimeType[extname] || 'text/plain' }); response.end(content, 'utf-8'); } }); }); server.on('listening', function(err) { if (err) throw err; console.log(Date() + ' Server is running...'); }); server.listen(7000);
配套前端调整
前端上传表单需要做以下配置:
- 表单action指向
/upload路径,method设为POST - 表单添加
enctype="multipart/form-data"属性 - 多文件上传时,文件input添加
multiple属性
内容的提问来源于stack exchange,提问作者Chitra
相关产品推荐
相关产品推荐

