How to use withCors middleware #16
Answered
by
georgeboot
georgeboot
asked this question in
Q&A
-
How should I use the I see there is a middleware, so I tried the following: import { Router } from 'itty-router'
import { json } from 'itty-router-extras'
import { withCors } from 'itty-router-extras/middleware/withCors'
const router = Router()
export default {
fetch: router.handle,
}
router.post('/scan', withCors, async (request, env) => {
// stuff here
return json({ success: true }, { status: 201 })
}) But this results in a (vague) error: {
"name":"TypeError",
"message":"Failed to execute function: parameter 1 is not of type 'Response'.",
"timestamp":1634115490880
} |
Beta Was this translation helpful? Give feedback.
Answered by
georgeboot
Oct 13, 2021
Replies: 1 comment 2 replies
-
How I solved it: // corshelper.js
export const handleCors = (options = {}) => request => {
const {
origin = '*',
methods = 'GET, POST, PATCH, DELETE',
headers = 'referer, origin, content-type',
maxAge = null,
allowCredentials = false,
} = options
if (
request.headers.get('Origin') !== null &&
request.headers.get('Access-Control-Request-Method') !== null
) {
const corsHeaders = {
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': methods,
'Access-Control-Allow-Headers': headers,
}
if (allowCredentials) {
corsHeaders['Access-Control-Allow-Credentials'] = 'true'
}
if (maxAge) {
corsHeaders['Access-Control-Max-Age'] = maxAge
}
// Handle CORS pre-flight request.
return new Response(null, {
status: 204,
headers: corsHeaders
})
}
// Handle standard OPTIONS request.
return new Response(null, {
headers: {
'Allow': `${methods}, HEAD, OPTIONS`,
}
})
}
export const wrapCorsHeader = (response, options = {}) => {
const {
origin = '*',
} = options
response.headers.set('Access-Control-Allow-Origin', origin)
return response
} // index.js
import { Router } from 'itty-router'
import { json } from 'itty-router-extras'
import { handleCors, wrapCorsHeader } from './corshelper'
const router = Router()
export default {
fetch: router.handle,
}
router.options('/scan', handleCors({ methods: 'POST', maxAge: 86400 }))
router.post('/scan', async (request, env) => {
// stuff here
return wrapCorsHeader(
json({ success: true }, { status: 201 })
)
}) |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
georgeboot
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How I solved it: