Skip to content

Commit af5e1da

Browse files
committed
feat: enable CORS support
1 parent 65dfc79 commit af5e1da

File tree

4 files changed

+31
-3
lines changed

4 files changed

+31
-3
lines changed

package-lock.json

Lines changed: 20 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
},
4040
"dependencies": {
4141
"@tinyhttp/app": "^2.2.1",
42+
"@tinyhttp/cors": "^2.0.0",
4243
"chokidar": "^3.5.3",
4344
"dot-prop": "^8.0.2",
4445
"eta": "^3.2.0",

src/app.test.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ await test('createApp', async () => {
6565
{ method: 'GET', url: '/output.css', statusCode: 200 },
6666
{ method: 'GET', url: `/${file}`, statusCode: 200 },
6767

68+
// CORS
69+
{ method: 'OPTIONS', url: POSTS, statusCode: 204 },
70+
6871
// API
6972
{ method: 'GET', url: POSTS, statusCode: 200 },
7073
{ method: 'GET', url: POST_1, statusCode: 200 },

src/app.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { dirname, isAbsolute, join } from 'node:path'
22
import { fileURLToPath } from 'node:url'
33

44
import { App } from '@tinyhttp/app'
5+
import { cors } from '@tinyhttp/cors'
56
import { Eta } from 'eta'
67
import { Low } from 'lowdb'
78
import { json } from 'milliparsec'
@@ -29,15 +30,18 @@ export function createApp(db: Low<Data>, options: AppOptions = {}) {
2930
// Create app
3031
const app = new App()
3132

32-
// Body parser
33-
app.use(json())
34-
3533
// Static files
3634
app.use(sirv(join(__dirname, '../public'), { dev: !isProduction }))
3735
options.static
3836
?.map((path) => (isAbsolute(path) ? path : join(process.cwd(), path)))
3937
.forEach((dir) => app.use(sirv(dir, { dev: !isProduction })))
4038

39+
// CORS
40+
app.use(cors()).options('*', cors())
41+
42+
// Body parser
43+
app.use(json())
44+
4145
app.get('/', (_req, res) =>
4246
res.send(eta.render('index.html', { data: db.data })),
4347
)

0 commit comments

Comments
 (0)