-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
55 lines (47 loc) · 1.5 KB
/
server.js
File metadata and controls
55 lines (47 loc) · 1.5 KB
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
// server.js
import 'dotenv/config'
import express from 'express'
import mongoose from 'mongoose'
import cors from 'cors'
import todosRouter from './routes/todos.js'
const app = express()
// CORS Konfiguration für Vercel Frontend
const corsOptions = {
origin: function (origin, callback) {
// Erlaubte Origins
const allowedOrigins = [
'https://mern-to-do-app-six.vercel.app',
'http://localhost:3000',
'http://localhost:5173',
]
// Füge FRONTEND_URL hinzu, falls gesetzt
if (process.env.FRONTEND_URL) {
allowedOrigins.push(process.env.FRONTEND_URL)
}
// Debug: Log die Origin
console.log('CORS Request from origin:', origin)
console.log('Allowed origins:', allowedOrigins)
// Erlaube requests ohne origin (z.B. Postman, mobile apps)
if (!origin) return callback(null, true)
if (allowedOrigins.indexOf(origin) !== -1) {
callback(null, true)
} else {
console.log('CORS blocked origin:', origin)
callback(new Error('Not allowed by CORS'))
}
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
}
app.use(cors(corsOptions))
app.use(express.json())
app.use('/api/todos', todosRouter)
const PORT = process.env.PORT || 5000
mongoose
.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => app.listen(PORT, () => console.log('Server running on', PORT)))
.catch((err) => console.error(err))