Display an image returned by MockServer on a web page using React?

1.1k Views Asked by At

I am using Mock Server with OPEN API 3.0 to mock data & expectations. I need to fetch a dummy image using Mock Server as per the given sample on:

https://www.mock-server.com/mock_server/getting_started.html#button_response_literal_binary_PNG_body

I have the function definition with my swagger/ Open API swagger editor something like this:

/geo/{geo-id}:
    get:
      description: Geographic information
      tags: [caseload]
      parameters:
      - in: path
        name: geo-id
        required: true
        schema:
          type: string
      responses:
        '200':
          description: >
            Sample geographic map image in PNG format
          content:
            image/png:
              schema:
                type: string
                format: binary

With the sample REST API example as provided on the above link, I created my own mock data expectation CURL request like:

curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{
  "id": "geo-map",
  "httpRequest": {
    "method" : "GET",
    "path": "/geo/geoid-map"
  },
  "httpResponse": {
    "statusCode": 200,
    "headers": {
      "content-type": ["image/png"],
      "content-disposition": ["form-data; name=\"test.png\"; filename=\"test.png\""]
    },
    "body": {
      "type": "BINARY",
      "base64Bytes": "iVBORw0KGgoAAAANSUhEUgAAAqwAAAApCAIAAAB/QuwlAAAK+GlDQ1BJQ0MgUHJvZmlsZQAASA2tl3dcU8kWx+fe9EYLICAl9CZIr9JrAAXpYCMkgYQSYgoCVpTFFVwLKiKgrugiiIJrAWQtiAULoljAvkEWFXVdLIiKypvAEvfzPm//e5PP3Pne35w598zcmXzOBYBGZQmFWagKANkCiSg6xJ+RmJTMIDwGWKAF8EAf2LHYYqFfVFQE+NfyoRcg8s5bNnJf/2r2vztUOVwxGwAkCnancsTsbMjHYH3PFookAGDqoG68RCKUcxdkdREMELJMzumT/F7OqROMJU7YxEYHAIDVBYBIZbFE6QBQLaDOyGWnQz/UUMh2Ag5fADkPsjebx+JAboU8Izs7R85/QLZI/Yef9H8wi5Wq8MlipSt4ci5wJHxwIF8szGLlT9z8Py/ZWVK4XhPFEF6pPFFoNGwT4ZpVZ+aEK1iQOidySufDGU0xTxoaN8VscQBcy8mxHFZg+BRLM+P8ppglgvS3DV/CjJ1iUU60wr8ga458f0zEwOMyFcwVB8VM6Wn8YOYUF/BiE6Y4lx8/Z4rFmTGKGAp4AQpdJI1WxJwmClbMMVsMR/79XDbr+7MkvFj5O56Ih8MNDJpiriBOEY9Q4q/....[trimmed]
    }
  }
}'

Now, when I execute the request endpoint on the postman,

http://localhost:1080/geo/geoid-map, I am successfully able to fetch an image. But when trying the same on my react web app, the response returned by the API produces a console response:

axios.response

On expanding the response.data, it shows binary data something like:

enter image description here

Passing this binary image into react's src is unable to display the image.

Even after following config, as suggested in how to convert the binary data to image in reactjs & How to display binary data as image in React?, it does not work.

Any help regarding the same is appreciated

0

There are 0 best solutions below