var formData = {
name: 'TestDeck',
description: 'This is a test deck for my api',
private: false,
shareable: false,
ttsLanguages: [],
blacklistedSideIndices: [],
blacklistedQuestionTypes: [],
gradingModes: [],
imageAttribution: 'https://www.logogarden.com/wp-content/uploads/lg-index/Example-Logo-6.jpg',
imageFile: fs.readFile('retext.png', 'utf8')
}
function createDeck(connection) {
request.post({
url: '<url>',
formData: formData,
headers: {
'Content-Type': 'multipart/form-data'
},
json: true
}),
function(err, resp, body) {
}
}
我收到错误:类型错误:第一个参数必须是字符串或缓冲区。
老实说,我不知道为什么,需要帮助。
最佳答案
代码中有几个问题。
您收到
TypeError: First argument must be a string or Buffer
因为您试图在表单数据中发送 bool 值false
-- HTML 表单不会支持 bool 值。在 HTML 中,选中的复选框将发送其值,而未选中的复选框则不会。要解决此问题,您可以将
false
更改为'FALSE'
(string) 并在服务器端解析它。fs.readFile('retext.png', 'utf8')
的使用不正确。在表单中附加文件,正确的方法是:imageFile: fs.createReadStream('retext.png')
。当
formData: formData
用于request.post(...)
时,HTTP的Content-Type
请求将自动为multipart/form-data
,您无需再次定义Content-Type
header 。此外,设置
json: true
是不正确的,这会使Content-Type
成为application/json
。这种冲突会使request
模块困惑,并可能在某些 JavaScript 环境中引起问题。回调函数
function(err, resp, body){...}
应该是request.post(...)
的一部分,也许这是一个错字。
总而言之,正确的代码应该是这样的:
var formData = {
name: 'TestDeck',
description: 'This is a test deck for my api',
private: 'FALSE',
shareable: 'FALSE',
ttsLanguages: [],
blacklistedSideIndices: [],
blacklistedQuestionTypes: [],
gradingModes: [],
imageAttribution: 'https://www.logogarden.com/wp-content/uploads/lg-index/Example-Logo-6.jpg',
imageFile: fs.createReadStream('retext.png')
}
function createDeck(connection) {
request.post({
url: '<url>',
formData: formData
}, function(err, resp, body) {
})
}
关于javascript - 类型错误 : First argument must be a string or Buffer.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46134578/