CORS issue for published REST service

0
I have a microflow which I have published as a REST service with PUT method. On click on some button, I am performing two actions- Calling a nanoflow which internally executes JS action. In that JS action, I call my REST service. As nanoflow can not call microflow, and vice versa, I had to use XTTPRequest from JS to call my PUT method API.  But I am not able to call this API . Error i am getting in browse  console : OPTIONS http://localhost:8080/rest/addproducttorecent/v1/Product net::ERR_ABORTED 405 (Method Not Allowed) Access to XMLHttpRequest at 'http://localhost:8080/rest/addproducttorecent/v1/Product' from origin 'https://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. Seems like java script action calls my REST service with ‘OPTIONS’ method instead of ‘PUT’ method first. I have set option ‘Enable CORS’ as true in properties of published RESt service. What could be the solution here?
asked
2 answers
1

Hi Rushikesh,

When making rest calls in javascript the server has to respond to the preflight request (options method) with the correct headers (to authorize the browser) before the rest call can continue with the method that you are trying to use.

The header that you need is:

Access-Control-Allow-Origin

and sometimes you need a couple more if you want to use cookies. More info can be found here:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

In your published rest service you can create an operation for the “OPTIONS” request. Add that to your published service and create a microflow that creates the access-control-allow-origin header with the value of the url that you are access it from (or you can use an * but be cautious of using the wild card).

Here is an example:

https://modelshare.mendix.com/models/69eaf5f8-3658-4352-a0eb-00116f3746f5/options-resource

 

 

Hope this helps!

 

 

answered
2

You might want to use Mendix 8.1.

In the release notes, it says: “We changed the behavior of OPTIONS requests to published REST services. Authentication is no longer required when you define an OPTIONS microflow. In addition, when CORS is checked, you no longer need an OPTIONS microflows; the service will respond to OPTIONS requests with CORS headers.“

answered