Spe*_*int 1 javascript http request npm
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) {
}
}
Run Code Online (Sandbox Code Playgroud)
我收到错误消息:TypeError:第一个参数必须是字符串或Buffer。
老实说,我不知道为什么,需要帮助。
代码中有几个问题。
收到消息TypeError: First argument must be a string or Buffer是因为您试图false在表单数据中发送布尔值-HTML表单不支持布尔值。在HTML中,选中的复选框将发送其值,而未选中的复选框则不会。
要解决此问题,您可以更改false为'FALSE'(string)并在服务器端进行解析。
的使用fs.readFile('retext.png', 'utf8')不正确。要以表格形式附加文件,正确的方法是:imageFile: fs.createReadStream('retext.png')。
在formData: formData中使用时request.post(...),Content-TypeHTTP请求的将multipart/form-data自动使用,您无需Content-Type再次定义标头。
此外,它是不正确的设置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) {
})
}
Run Code Online (Sandbox Code Playgroud)