Skip to content

Commit

Permalink
Merge pull request #646 from osushi-academy/fix/cors-for-preview-doma…
Browse files Browse the repository at this point in the history
…in-2

プレビュー用のドメインからのCORSを許可
  • Loading branch information
yuta-ike authored Jan 4, 2022
2 parents 3947c04 + 8c353d1 commit b6b48cc
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 6 deletions.
7 changes: 2 additions & 5 deletions app/server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import StampFactory from "./infra/factory/StampFactory"
import AdminService from "./service/admin/AdminService"
import AdminAuth from "./infra/auth/AdminAuth"
import cors from "cors"
import { CORS_OPTION } from "./utils/http"

const app = express()
const httpServer = createServer(app)
Expand Down Expand Up @@ -65,11 +66,7 @@ httpServer.listen(PORT, () => {
})

// ref: https://www.npmjs.com/package/cors#configuring-cors
const corsOption = {
origin: process.env.CORS_ORIGIN ?? "http://localhost:3000",
optionsSuccessStatus: 200,
}
const myCors = () => cors(corsOption)
const myCors = () => cors(CORS_OPTION)
// NOTE: genericsでstringを指定しないと、オーバーロードがマッチしなくて型エラーが起こる
app.options<string>("*", myCors())
app.use(myCors())
Expand Down
3 changes: 2 additions & 1 deletion app/server/src/ioServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { DefaultEventsMap } from "socket.io/dist/typed-events"
import IStampFactory from "./domain/stamp/IStampFactory"
import IAdminAuth from "./domain/admin/IAdminAuth"
import AdminAuth from "./infra/auth/AdminAuth"
import { CORS_OPTION } from "./utils/http"

export class GlobalSocket extends Server<
DefaultEventsMap,
Expand All @@ -51,7 +52,7 @@ const createSocketIOServer = async (
) => {
const io = new GlobalSocket(httpServer, {
cors: {
origin: process.env.CORS_ORIGIN ?? "http://localhost:3000",
...CORS_OPTION,
methods: ["GET", "POST"],
credentials: true,
},
Expand Down
7 changes: 7 additions & 0 deletions app/server/src/utils/http.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const CORS_OPTION = {
origin: [
process.env.CORS_ORIGIN ?? "http://localhost:3000",
new RegExp(process.env.CORS_ORIGIN_PREVIEW ?? "", "i"),
],
optionsSuccessStatus: 200,
}

0 comments on commit b6b48cc

Please sign in to comment.