Add CORS preflight and headers

Signed-off-by: Joe Ma <rikkaneko23@gmail.com>
This commit is contained in:
Joe Ma 2024-02-03 03:11:17 +08:00
parent 8aac6f87a9
commit 6be1e97122
No known key found for this signature in database
GPG key ID: 7A0ECF5F5EDC587F
2 changed files with 32 additions and 3 deletions

View file

@ -189,11 +189,11 @@ Generate the presigned URL for upload large paste to the given S3 endpoint `LARG
The `file-size` and `file-sha256sum` field is required.
### POST /v2/large_upload/complete/<uuid>
### POST /v2/large_upload/complete/\<uuid\>
Finialize the paste created from `/v2/large_upload/create`.
### GET /v2/large_upload/<uuid>
### GET /v2/large_upload/\<uuid\>
Generate the presigned URL for upload large paste to the given S3 endpoint `LARGE_DOWNLOAD_ENDPOINT` using HTTP `GET` request.

View file

@ -27,6 +27,22 @@ import { get_presign_url, router as large_upload } from './v2/large_upload';
const router = Router<ERequest, [Env, ExecutionContext]>();
// Handle preflighted CORS request
router.options('*', (request) => {
const url = new URL(request.url);
// Allow all subdomain of nekoid.cc
if (url.hostname.endsWith('nekoid.cc')) {
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': url.origin,
'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',
'Vary': 'Origin',
}
})
}
});
// Shared common properties to all route
router.all('*', (request) => {
// Detect if request from browsers
@ -530,5 +546,18 @@ router.all('*', () => {
});
export default {
fetch: (req: Request, env: Env, ctx: ExecutionContext) => router.handle(req, env, ctx).catch(error),
fetch: (req: Request, env: Env, ctx: ExecutionContext) =>
router
.handle(req, env, ctx)
.catch(error)
// Apply CORS headers
.then((res: Response) => {
const url = new URL(req.url);
// Allow all subdomain of nekoid.cc
if (url.hostname.endsWith('nekoid.cc')) {
res.headers.set('Access-Control-Allow-Origin', url.origin);
res.headers.set('Vary', 'Origin');
}
return res;
}),
};