Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

POST formData with executeHttpRequest #2450

Closed
nocin opened this issue May 5, 2022 · 2 comments
Closed

POST formData with executeHttpRequest #2450

nocin opened this issue May 5, 2022 · 2 comments
Labels
bug Something isn't working

Comments

@nocin
Copy link

nocin commented May 5, 2022

Hi Cloud SDK Team,

Describe the bug
I already posted a question in the CAP Forum a few months ago which explains what I'm trying to archive and also what I tried so far.
https://answers.sap.com/questions/13551972/posting-formdata-to-external-rest-api.html

I have an API which I try to post a file to using formData. I can successfully use the API via Postman or using fetch.
Then I tried the same using CDS and now also directly using executeHttpRequest.

To Reproduce
Unfortunately I have no public API which I can provide for testing.

Expected behavior
Of course the API should accept my formData query send via executeHttpRequest. :-)
The API Endpoint converts the file and the content-type of the response is for example:
Content-Type: multipart/mixed;boundary=Boundary_682_1571866230_1651741380254
As already said, this works fine using fetch (see my posted question) and the problem seems to be on the sending side.

Used Versions:

  • node version via node -v
    v14.17.6
  • npm version via npm -v
    6.14.15
  • SAP Cloud SDK version you used as dependency
    1.54.0

Code Examples

Using CDS:

    const myAPI= await cds.connect.to('myDestination')
    const health = await myAPI.get("/health") 
    console.log(">>> Health ", health.status) // a GET request works fine

    try {
        const imageBuffer = fs.readFileSync('./tux.png')
        const form = new FormData()
        form.append('file', imageBuffer, {
            contentType: 'text/plain',
            name: 'file',
            filename: 'tux.png'
        })
        const response = 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
    }

Using executeHttpRequest:

 const health = await executeHttpRequest(
        { destinationName: 'myDestination' },
        { method: 'get', url: '/health', params: {} }
 )
 console.log(">>> Health ", health.data.status) // a GET request works fine

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

        const response = await executeHttpRequest(
            { destinationName: 'myDestination' },
            { method: 'post', url: '/my/api/path', headers: { 'Content-Type': 'multipart/form-data', 'Accept': '*/*', 'Content-Length': imageBuffer.length }, data: form }
        )
        console.log(response.data)
    } catch (err) {
        console.log("Error message: " + err.message) //Request failed with status code 404
    }

Tried adding different headers, without success.
One thing to note, using Postman the Content-Type always includes the boundary, e.g.:
Content-Type: multipart/form-data; boundary=--------------------------817648025188283885837797
I tried adding it manually while debugging, but also no success.

Log file
Error message always returned: "Request failed with status code 404"
From wiki:

The 404 or Not Found error message is a HTTP standard response code indicating that the client was able to communicate with the server, but the server could not find what was requested. so, your code is OK, but server cannot find resource you are looking for. Double check if your url is correct.

It defnitly can reach the API enpoint as it returns a Payara error message (the endpoint service runs on a Payara Server):

'<title>Payara Server 5.2021.3 #badassfish - Error report</title><style type="text/css"></style>

HTTP Status 404 - Not Found


type Status report

messageNot Found

descriptionThe requested resource is not available.


Payara Server 5.2021.3 #badassfish

'

Unfortunaltely until now I didn't had the chance to check on Payara server side, if anything and what exacly arrives at the endpoint. It seems that the request is not correct when send to the endpoint.

best regads
Nico

@nocin nocin added the bug Something isn't working label May 5, 2022
@nocin
Copy link
Author

nocin commented May 5, 2022

As it works with fetch, I tried to do the same via axios directly.
Also I figured out how add the correct Content-Type using form.getHeaders().
It sill fails, so may be it's a problem with axios itself and not the cloud-sdk. At least these issues sound a bit like it
axios/axios#4406
axios/axios#318
Therefore I'm closing and will do some further testing.

    const imageBuffer = fs.readFileSync('./tux.png')

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

    const headers = {
        'Authorization': 'Basic ' + btoa(user + ':' + password),
        ...form.getHeaders()
    }

    try {
        /* const response = await axios({
                    method: 'POST',
                    url: url,
                    headers: headers,
                    data: form
                }) */

        const response = await axios.post(url, form, {
            headers: headers,
            transformRequest: form => form,
        })
    } catch (err) {
        console.log("Error message: " + err.message) 
        console.log(err.response.data)
    }

@marikaner
Copy link
Contributor

@nocin The two issues you linked in your comment seem to be resolved now. Is this sill an issue for you?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants