nhttp_cors (nhttp v1.0.0)
View SourceCross-Origin Resource Sharing (CORS) helpers for nhttp.
Provides convenience functions for handling CORS preflight requests and adding CORS headers to responses.
Simple CORS
handle_request(#{method := options}, State) ->
{reply, nhttp_cors:preflight(<<"*">>), State};
handle_request(Req, State) ->
Response = nhttp_resp:ok(Headers, Body),
CorsHeaders = nhttp_cors:headers(<<"*">>),
{reply, Response#{headers := CorsHeaders ++ maps:get(headers, Response)}, State}.Advanced CORS
Opts = #{
methods => [<<"GET">>, <<"POST">>, <<"PUT">>, <<"DELETE">>],
headers => [<<"content-type">>, <<"authorization">>],
max_age => 86400,
credentials => true
},
Response = nhttp_cors:preflight(Origin, Opts).
Summary
Functions
Get CORS headers for the given origin with default options.
Get CORS headers with custom options. Options
Create a preflight response for the given origin with default options. Returns a 204 No Content response with appropriate CORS headers.
Create a preflight response with custom options.
Types
-type opts() :: #{credentials => boolean(), expose_headers => [binary()], headers => [binary()], max_age => non_neg_integer(), methods => [binary()]}.
Functions
-spec headers(binary()) -> nhttp_lib:headers().
Get CORS headers for the given origin with default options.
-spec headers(binary(), opts()) -> nhttp_lib:headers().
Get CORS headers with custom options. Options:
methods- List of allowed methods (default: GET, POST, OPTIONS)headers- List of allowed request headers (default: content-type)expose_headers- List of headers to expose to the clientmax_age- Preflight cache duration in secondscredentials- Whether to allow credentials (cookies, auth)
-spec preflight(binary()) -> nhttp_lib:response().
Create a preflight response for the given origin with default options. Returns a 204 No Content response with appropriate CORS headers.
-spec preflight(binary(), opts()) -> nhttp_lib:response().
Create a preflight response with custom options.