-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.lua
67 lines (50 loc) · 1.59 KB
/
init.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
function create (opts)
opts = opts or {}
opts.allowMethods = opts.allowMethods or 'GET,HEAD,PUT,POST,DELETE,PATCH'
function cors (req, res, nxt)
local origin
if (type(opts.origin) == 'function') then
origin = opts.origin(req, res)
else
origin = opts.origin or '*'
end
if req.method ~= 'OPTIONS' then
-- Simple Cross-Origin Request, Actual Request, and Redirects
res:setHeader('Access-Control-Allow-Origin', origin)
if opts.credentials then
res:setHeader('Access-Control-Allow-Credentials', 'true')
end
if opts.exposeHeaders then
res:setHeader('Access-Control-Expose-Headers', opts.exposeHeaders)
end
nxt()
else
-- Preflight Request
if not req.headers['Access-Control-Request-Method'] then
-- this not preflight request, ignore it
return nxt()
end
res:setHeader('Access-Control-Allow-Origin', origin)
if opts.credentials then
res:setHeader('Access-Control-Allow-Credentials', 'true')
end
if opts.maxAge then
res:setHeader('Access-Control-Max-Age', opts.maxAge);
end
if opts.allowMethods then
res:setHeader('Access-Control-Allow-Methods', opts.allowMethods);
end
local allowHeaders = opts.allowHeaders
if not allowHeaders then
allowHeaders = req.headers['Access-Control-Request-Headers']
end
if allowHeaders then
res:setHeader('Access-Control-Allow-Headers', allowHeaders)
end
res:writeHead(204)
res:finish()
end
end
return cors
end
return create