简体   繁体   中英

Unable to properly add a file header on a POST request using axios in a node application

I'm trying to convert the following curl syntax to node.js using axios:

curl -X POST "https://my-target-baseURL.com/elements/api/files? 
path=%2Fmy-file&folderId=1234" 
-H "accept: application/json" 
-H "Authorization: SomeHeader 1234, OtherHeader 1234" 
-H "content-type: multipart/form-data" 
-F "file=@my-file.png;type=image/png"

In oder to convert this, I'm doing the following.

    const fileInfo = path.parse(req.file.filename)
    const fileFullName = fileInfo.name + fileInfo.ext
    const folder_id = req.query.id
    const readFile = util.promisify(fs.readFile)
    const fullPath = path.join(__dirname, '..', 'someDirectory', fileFullName)
    const file_to_upload = await readFile(`${fullPath}`)

    try {
      const uploaded_file = await axios.post(`${my-target-baseURL.com}/elements/api/files?path=%2F${fileFullName}&folderId=${folder_id}`,
      file_to_upload,
      { headers: { 'accept': 'application/json', Authorization: `SomeHeader xyz, OtherHeader xyz`, 
      'content-type':'multipart/form-data',},
    })
      console.log('uploaded_file: ', uploaded_file.data)
    }
    catch(error) {
        throw new Error(error)
    }

Upon doing this, I get a 500 error ( Unhandled promise rejection (rejection id: 2): Error: Error: Request failed with status code 500 ).

One small thing to mention here is that the way I'm reading the file works fine. The reason I say this is because this piece of code used to read the file just like this and hit another API and got a response without any sort of problem.

I'm unable to find what's causing this problem. Is there something wrong with the way I'm converting the curl to the axios call? Am I doing the conversion for -F "file=@my-file.png;type=image/png" correctly?

This looks good to me, can you copy your request as CURL when you try it and add the result?

Also it's cleaner to break header out into something like

const headers = {
    'Accept': 'application/json', 
    'Authorization': `SomeHeader xyz, OtherHeader xyz`,
    'Content-Type':'multipart/form-data'
    }

and then do

await axios.post(`${my-target-baseURL.com}/elements/api/files?path=%2F${fileFullName}&folderId=${folder_id}`,
      file_to_upload,
      {headers});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM