Skip to Content
0
Dec 23, 2021 at 10:23 AM

Posting FormData to external REST API

1389 Views Last edit May 05, 2022 at 09:39 AM 8 rev

Hi CAP Community,

I'm trying to Post a file as FormData to an external rest API. I'm following the documentation here: https://cap.cloud.sap/docs/node.js/services#srv-send

Using fetch it was pretty straight forward and is working fine:

        const imageBuffer = fs.readFileSync('./testfiles/filename.png')

        const form = new FormData()
        form.append('file', imageBuffer, {
            contentType: 'text/plain',
            name: 'file',
            filename: 'filename.png'
        })

        const headers = {
            'Authorization': 'Basic ' + btoa(process.env.LOGIN)
        }

        const url = process.env.URL + '/my/api/path' 

        const response = await fetch(url, {
            method: 'POST',
            headers: headers,
            body: form,
        })

        if (!response.ok) throw new Error(`unexpected response ${response.statusText}`)  
        //hurray, it works

Next I added the api connection information to the package.json:

  "cds": {
    "requires": {
      "myAPI": {
        "kind": "rest",
        "credentials": {
          "url": ...,
          "authentication": "BasicAuthentication",
          "username": ...,
          "password": ...,
          "requestTimeout": 30000
        }
      }
   }
 }

and tried to archive the same using cds.connect and cds.post/cds.send

    this.on('submitFile', async req => {
        const imageBuffer = fs.readFileSync('./testfiles/filename.png')

        const form = new FormData()
        form.append('file', imageBuffer, {
           contentType: 'text/plain',
           name: 'file',
           filename: 'filename.png'
        })

        try {
            const myAPI = await cds.connect.to('myAPI')

            //Does not work
            const response1 = await myAPI.post('/my/api/path', form)

            //Does not work either
            const response2 = await myAPI.send({
               method: 'POST',
               path: '/my/api/path',
               data: form
            })
       } catch (err) {
            console.log("Error message: " + err.message) //Error during request to remote service: Request failed with status code 404
        }
    })

but no success. Does anyone has an idea what I'm doing wrong? Is FormData not supported as payload?

Thanks & Regards
Nico