Two templates needed for stubbing Cross-origin request
When a site makes a cross-origin ajax request, the browser makes 2 calls to the destination URL under the hood. The first call is a request with the OPTIONS HTTP verb, to which the webserver sends back appropriate Access-Control headers which determine whether the webserver will accept the next request. This is followed by the actual request.
When mocking such a cross origin request, we need to populate mirage with two templates. Below is an example of what we had to do for a simple POST request for example:
mirage.put('/api/endpoint', "") do
http_method :options
headers "Access-Control-Allow-Headers" => "Origin, X-Requested-With, Content-Type",
"Access-Control-Allow-Methods" => "POST",
"Access-Control-Allow-Origin" => "*"
end
mirage.put('/api/endpoint', {response: :body}.to_json) do
http_method :post
end
Might be worth having a DSL method for doing it in one go. If not then might be worth having it somewhere in the README as a recipe for front-end cross-origin testing.
Hi @asehra,
Thanks for this. What do you think the method might look like?
Either way, this is informative and some documentation is a good idea.
I'll give this some thought. First thoughts are that it's important to not contrive a fake non HTTP type concept to model this capability. Maybe a DSL external to the client? Maybe the concept of some kind of TemplateBundle?
First thoughts for me were to just make a client thing. Like a cross_origin option passed within args to put that is passed to Templates class. But, looking at put within templates.rb it feels like it is doing too much already. So not sure if it is a good suggestion.
Didn't quite understand what you meant by fake non HTTP type concept. Did you mean Cross-origin bits or the OPTIONS verb?
Also, not sure if it is a frequent requirement. So don't know if it is a bit premature to add any new concepts. Maybe a how to guide in wiki/readme will be sufficient.