swagger-express-middleware
swagger-express-middleware copied to clipboard
Is there any way to set global responses or CORS
My GET
POST
requests are changed to OPTIONS
by CORS
preflight.
Cause my request is cross-domain, header-setted and with-credentials.
I've searched a lot to solve this problem, but failed.
Thus, I gave up to avoid this and try to make my request allow OPTIONS.
But I only found it able to set options for every path. I've also tried to use regexp to match all path, which seems not supported yet.
Is there any way to set global responses for all path or somethings else to avoid automatically send request by OPTIONS
method?
Any ideas?
Just to clarify... requests don't get "changed" to OPTIONS
by CORS. The OPTIONS
request is a separate request that occurs prior to the normal request. So, if a script in a web browser sends a request like POST /some/api
, then the browser actually sends two requests. The first request is OPTIONS /some/api
, and the second request is POST /some/api
.
The second request will only be sent if the response from the first request says it's allowed. That's what the CORS middleware takes care of for you. It automatically replies to the OPTIONS
request and tells the browser whether the second request is allowed or not, based on your Swagger API definition. So you don't specifically need handle the OPTIONS
request yourself at all. And you don't necessarily need to include the OPTIONS
requests in your Swagger definition.
@BigstickCarpet
Yes, you are right and thanks a lot for your explicit explain. OPTIONS is pre-sended for some verify reason. Then followed normal request.
Everything works functionally ok. But there will be warning of swagger which says my request path does not have operation matches OPTIONS.
To avoid this warning, I add an options operation like post, get or other method defined under /my/path.
Is there any way to add an options operation in some global aspect so I only have to add it once but actually matches all paths.
The Swagger Spec allows you to use $ref
to re-use anything in your API spec. So you could just define the OPTIONS
method once, and then reference it everywhere else using $ref
. It's not quite as nice as just saying "add an OPTIONS
method all of my paths", but it's better than manually re-typing the entire method definition over and over again