Node.js使用request-promise+form-data报TypeError: Cannot read property 'name' of null求助
解决Node.js中request-promise + form-data提交的
Cannot read property 'name' of null错误 我来帮你排查这个问题,从错误栈和代码来看,核心问题是form-data处理文件字段时缺少必要的文件名参数,再加上请求配置里的几个冲突设置导致的。下面一步步拆解问题并给出修复方案:
问题根源分析
文件字段缺少文件名:
当你向FormData添加Buffer类型的文件时,必须指定文件名参数,否则form-data库在生成Content-Disposition请求头时,会找不到name属性,直接抛出Cannot read property 'name' of null错误。请求头配置完全错误:
- 你设置了
Content-Type: application/json,但实际要发送的是multipart/form-data,这个头会被form-data自动生成(包含boundary分隔符),手动设置反而会干扰正常处理。 enctype不是HTTP请求头的标准字段,这是HTML表单的属性,不需要在请求头里添加。Access-Control-Allow-Origin和Access-Control-Allow-Methods是服务器返回给浏览器的响应头,你作为请求方根本不需要发送这些头。
- 你设置了
json: true配置冲突:
这个选项会让request-promise强制把请求体序列化为JSON,并且期望响应是JSON,但你实际是发送form-data,两者完全冲突,必须去掉。request-promise调用冗余:
request-promise本身就返回Promise,不需要额外调用.promise()。异步函数调用未加await:
在fetchAllData里调用sendToAPI时没有加await,会导致API请求脱离当前异步流程,可能出现未捕获的错误。
修复后的完整代码
const requestPromise = require('request-promise'); const FormData = require('form-data'); const uuidv4 = require('uuid').v4; const date = require('date-and-time'); var sendToAPI = async (fileObjBuffer, myId, timestamp) => { let formData = new FormData(); // 关键修复:给fileData字段添加文件名参数 formData.append('fileData', fileObjBuffer, { filename: `${timestamp}.txt` }); formData.append('myId', myId); formData.append('fileName', timestamp); let options = { method: 'POST', uri: '<URL>', // 替换为你的实际API地址 formData: formData, // 只保留必要的请求头(比如如果需要授权就加Authorization) headers: { // 示例:如果API需要token,可以在这里添加 // 'Authorization': 'Bearer your-token-here' }, // 移除json: true,因为发送的是form-data simple: true, // HTTP状态码非2xx时自动抛出错误 resolveWithFullResponse: false // 只返回响应体,不需要完整响应对象 }; try { let apiResult = await requestPromise(options); // 直接await即可 console.log('\n\napiResult: ', apiResult); return apiResult; } catch (error) { console.error('error in sending to api: ', error); throw error; // 抛出错误让调用方处理 } } var fetchAllData = async () => { let query = 'select * from demo_db.demo_table;'; try { // 执行Cassandra查询 const result = await client.execute(query, [], { prepare: true }); // 用map+join优化字符串拼接性能,避免多次字符串累加 const rowsContent = result.rows.map(resultObj => `${resultObj.room_id}:${resultObj.message_id}:${resultObj.original_message}:${resultObj.send_date}:${resultObj.sender}` ).join("%"); // 用Buffer.from代替new Buffer(new Buffer已被废弃) let fileObjBuffer = Buffer.from(rowsContent); let myId = uuidv4(); let timestamp = date.format(new Date(), 'YYYYMMMDDhhmmss', false); await sendToAPI(fileObjBuffer, myId, timestamp); // 添加await,确保API请求完成 console.log("Data sent to API successfully"); } catch (error) { console.error('error in fetching data or sending to API: ', error); } }
额外优化点
- 用
Buffer.from()代替new Buffer():后者已经被Node.js废弃,前者更安全规范。 - 用
map+join代替循环累加字符串:性能更优,代码更简洁。 - 在
sendToAPI里抛出错误:让调用方(fetchAllData)统一处理错误,避免错误被吞掉。
内容的提问来源于stack exchange,提问作者Bhushan Mahajan
相关产品推荐
相关产品推荐

