Add common CORS headers in Mountebank responses

297 views Asked by At

React app that is using mounteback as mock server, I am getting this error

Access to fetch at 'http://localhost:8080/xxx/api/secured/policies' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I managed to find this with regards to OPTIONS pre-flight https://groups.google.com/g/mountebank-discuss/c/G7TRM87Pocs

But even this is not enough, I had to had:

{
    "is": {
    "headers": {
      "Content-Type": "application/json",
      "Access-Control-Allow-Headers": "*",
      "Access-Control-Allow-Methods": "*",
      "Access-Control-Allow-Origin": "*"
    }
  }, ...truncated...,

}

For all the response stubs (I tried one and works, so means I need to do it for all). Is there any way I can add this headers in one central location so that I don't need to add this to all stubs (its an existing project with half-baked mocks, that are not working, had to use CORS-unblock plugin without this change)?

1

There are 1 answers

0
Carlos Jaime C. De Leon On

I found the solution which is using the defaultResponse field which will return the CORS setting whenever no stub match is found. Additionally if a stub match exists, it merges the stub response with defaultResponse hence all stubs will have this CORS settings in a central location as per my requirement.

According to docs:

"The default response to send if no predicate matches. Also represents the default values that get merged into a response that doesn't specify every field"

http://www.mbtest.org/docs/protocols/http

This is the solution that I have landed and works for me (no need to add CORS to each individual stub):

{
"imposters": [
    {
      "port": 8080,
      "protocol": "http",
      "defaultResponse": {
        "headers": {
          "Content-Type": "application/json",
          "Access-Control-Allow-Headers": "*",
          "Access-Control-Allow-Methods": "*",
          "Access-Control-Allow-Origin": "*"
        }
      },
      "stubs": [
        <% include policy/sample1.json %> <%# truncated the list of json files which was about 20+ %>
      ]
    }
  ]
}