W
Wasp2mo ago
NEROX

CORS issue

@kapa.ai i'm experiencing a CORS issue: Access to XMLHttpRequest at 'https://api.elmossetgourmet.es/auth/me' from origin 'https://elmossetgourmet.es' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.Understand this errorAI api.elmossetgourmet.es/auth/me:1

Failed to load resource: net::ERR_FAILEDUnderstand this errorAI /checkout:1 Access to XMLHttpRequest at 'https://api.elmossetgourmet.es/operations/create-stripe-checkout-session' from origin 'https://elmossetgourmet.es' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.Understand this errorAI index-C393RbYu.js:169 Error al procesar el pago: At {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …} g @ index-C393RbYu.js:169 await in g Oe @ index-C393RbYu.js:37 Ge @ index-C393RbYu.js:37 ct @ index-C393RbYu.js:37 S1 @ index-C393RbYu.js:37 A1 @ index-C393RbYu.js:37 (anonymous) @ index-C393RbYu.js:37 Sf @ index-C393RbYu.js:40 Ta @ index-C393RbYu.js:37 kh @ index-C393RbYu.js:37 nh @ index-C393RbYu.js:37 f4 @ index-C393RbYu.js:37Understand this errorAI index-C393RbYu.js:78

POST https://api.elmossetgourmet.es/operations/create-stripe-checkout-session net::ERR_FAILED My middleware.ts: import type { Application } from 'express' import cors from 'cors' export const configureMiddleware = (app: Application) => { // Habilitar CORS para todas las solicitudes app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', 'https://elmossetgourmet.es') res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS') res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization') res.header('Access-Control-Allow-Credentials', 'true') // Manejar solicitudes preflight OPTIONS if (req.method === 'OPTIONS') { return res.status(200).send() } next() }) // Configuración específica para rutas de autenticación app.use('/auth/*', (req, res, next) => { res.header('Access-Control-Allow-Origin', 'https://elmossetgourmet.es') res.header('Access-Control-Allow-Credentials', 'true') next() }) // Configuración específica para rutas de operaciones (incluyendo Stripe) app.use('/operations/*', (req, res, next) => { res.header('Access-Control-Allow-Origin', 'https://elmossetgourmet.es') res.header('Access-Control-Allow-Credentials', 'true') next() }) // Middleware de CORS general como respaldo app.use(cors({ origin: 'https://elmossetgourmet.es', credentials: true, methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept', 'Origin'], preflightContinue: false, optionsSuccessStatus: 204 })) }
10 Replies
kapa.ai
kapa.ai2mo ago
Hi @NEROX. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Based on the information provided in the knowledge sources and your question, it appears you're experiencing a CORS (Cross-Origin Resource Sharing) issue with your Wasp application. Let's address this problem step by step: 1. CORS Configuration in Wasp: Wasp provides built-in CORS support, but it seems your custom configuration is not working as expected. According to the Wasp documentation on configuring middleware (https://wasp-lang.dev/docs/advanced/middleware-config#1-customize-global-middleware), you can customize the global middleware to modify CORS settings. 2. Suggested Solution: Instead of creating a separate middleware.ts file, try modifying the CORS configuration directly in your Wasp project. Here's how you can do it: In your main.wasp file, add the following:
app todoApp {
// ...
server: {
setupFn: import setup from "@src/serverSetup",
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}
app todoApp {
// ...
server: {
setupFn: import setup from "@src/serverSetup",
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}
Then, create a serverSetup.js (or .ts if you're using TypeScript) file in your src directory:
import cors from 'cors'
import { config } from 'wasp/server'

export const serverMiddlewareFn = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: '<https://elmossetgourmet.es',>
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept', 'Origin'],
}))
return middlewareConfig
}
import cors from 'cors'
import { config } from 'wasp/server'

export const serverMiddlewareFn = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: '<https://elmossetgourmet.es',>
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept', 'Origin'],
}))
return middlewareConfig
}
This configuration should allow requests from <https://elmossetgourmet.es> and set the necessary CORS headers. 3. Additional Considerations: - Make sure your server is actually running on <https://api.elmossetgourmet.es.> The CORS configuration needs to be applied on the server that's receiving the requests. - If you're using custom API endpoints, you might need to apply CORS configuration to them specifically. See the Wasp documentation on making sure CORS works for APIs (https://wasp-lang.dev/docs/advanced/apis#making-sure-cors-works) for more details. 4. Preflight Requests: Your error message mentions a preflight request issue. The configuration above should handle OPTIONS requests, but if you're still having issues, you might need to explicitly handle preflight requests in your API implementations. If these steps don't resolve your issue, it's possible that there's a more complex configuration needed or there might be other factors at play. In that case, you might want to reach out to the Wasp community on their Discord channel (https://discord.gg/rzdnErX) for more specific help. Remember, CORS is a security feature implemented by browsers, so it's crucial to configure it correctly to allow only the necessary origins while maintaining security. Wasp Docs: Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config#1-customize-global-middleware) Wasp Docs: Making Sure CORS Works for APIs (https://wasp-lang.dev/docs/advanced/apis#making-sure-cors-works) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @NEROX, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
NEROX
NEROXOP2mo ago
Thx Kapa!
Filip
Filip2mo ago
Great to see the bot's doing its job
Stefan Vitória
@kapa.ai i am facing the same issue but this doesnt seems to work for me. I am on localhost but still facing this error
kapa.ai
kapa.ai4w ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- I understand you're facing a similar CORS issue while working on localhost. Let's address this specific scenario based on the information available in the knowledge sources. For localhost development, Wasp should automatically handle CORS for you. However, if you're still encountering issues, there are a few things we can try: 1. First, make sure you're using the latest version of Wasp. You can update Wasp by running:
curl -sSL <https://get.wasp-lang.dev/installer.sh> | sh

curl -sSL <https://get.wasp-lang.dev/installer.sh> | sh

Then, update the Wasp version in your main.wasp file:
app yourApp {
wasp: {
version: "^0.11.8"
},
// ... other configurations
}

app yourApp {
wasp: {
version: "^0.11.8"
},
// ... other configurations
}

2. If you're using custom API endpoints, you might need to explicitly configure CORS for them. Here's how you can do that: In your main.wasp file, add an apiNamespace:
apiNamespace myApi {
middlewareConfigFn: import { apiMiddleware } from "@src/apis",
path: "/api"
}

apiNamespace myApi {
middlewareConfigFn: import { apiMiddleware } from "@src/apis",
path: "/api"
}

Then, in your src/apis.js (or .ts) file:
import cors from 'cors'
import { config } from 'wasp/server'

export const apiMiddleware = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: config.frontendUrl,
credentials: true
}))
return middlewareConfig
}

import cors from 'cors'
import { config } from 'wasp/server'

export const apiMiddleware = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: config.frontendUrl,
credentials: true
}))
return middlewareConfig
}

This configuration should allow requests from your frontend URL, which for localhost development should be automatically set by Wasp. 3. If you're still facing issues, you can try to manually set the CORS configuration for all routes: In your main.wasp file:
app yourApp {
// ...
server: {
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}

app yourApp {
// ...
server: {
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
}

Then in src/serverSetup.js:
import cors from 'cors'
import { config } from 'wasp/server'

export const serverMiddlewareFn = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: [config.frontendUrl, '<http://localhost:3000'],>
credentials: true
}))
return middlewareConfig
}

import cors from 'cors'
import { config } from 'wasp/server'

export const serverMiddlewareFn = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: [config.frontendUrl, '<http://localhost:3000'],>
credentials: true
}))
return middlewareConfig
}

This configuration explicitly allows requests from both the Wasp-configured frontend URL and <http://localhost:3000.> Remember, when working with localhost, your frontend and backend URLs should typically be: - Frontend: <http://localhost:3000> - Backend: <http://localhost:3001> If you're still encountering issues after trying these solutions, it might be helpful to check your browser's console for more specific error messages. Also, ensure that your backend is actually running on the expected port. If the problem persists, you may want to create a minimal reproducible example and seek further assistance from the Wasp community on their Discord channel (https://discord.gg/rzdnErX). Wasp Docs: Making Sure CORS Works (https://wasp-lang.dev/docs/advanced/apis#making-sure-cors-works) Wasp Docs: Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config#1-customize-global-middleware) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Stefan Vitória, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Stefan Vitória
i am on wasp 0.14.2 @kapa.ai i am on wasp 0.14.2
kapa.ai
kapa.ai4w ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- Thank you for providing that information. Since you're using Wasp version 0.14.2, which is more recent than the versions mentioned in the previous conversation, let's adjust our approach accordingly. For Wasp 0.14.2, the CORS configuration process is similar, but there might be some slight differences or improvements. Here's what you can try: 1. First, ensure that your main.wasp file includes the server configuration:
app yourApp {
wasp: {
version: "^0.14.2"
},
server: {
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
// ... other configurations
}
app yourApp {
wasp: {
version: "^0.14.2"
},
server: {
middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup"
},
// ... other configurations
}
2. Then, in your src/serverSetup.js (or .ts if you're using TypeScript), configure the CORS middleware:
import cors from 'cors'
import { config } from 'wasp/server'

export const serverMiddlewareFn = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: [config.frontendUrl, '<http://localhost:3000'],>
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}))
return middlewareConfig
}
import cors from 'cors'
import { config } from 'wasp/server'

export const serverMiddlewareFn = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: [config.frontendUrl, '<http://localhost:3000'],>
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}))
return middlewareConfig
}
This configuration should allow CORS for both the Wasp-configured frontend URL and explicitly for <http://localhost:3000.> If you're still experiencing CORS issues after applying these changes, it would be helpful to know more details about your specific setup and the exact error messages you're seeing. Also, keep in mind that Wasp is actively developed, and there might be changes or improvements in CORS handling in version 0.14.2 that are not fully documented yet. If these steps don't resolve your issue, I recommend checking the official Wasp documentation (https://wasp-lang.dev/docs) for any version-specific information, or reaching out to the Wasp community on their Discord channel (https://discord.gg/rzdnErX) for the most up-to-date advice. Wasp Docs: Configuring Middleware (https://wasp-lang.dev/docs/advanced/middleware-config#1-customize-global-middleware) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Stefan Vitória, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Stefan Vitória
@kapa.ai this is the api declaration: api scanQrCodeForMemberValidation { httpRoute: (POST, "/api/validateQrCodeScan"), fn: import {scanQrCodeForMemberValidation} from "@src/server/member-validation/api", entities: [Gym, Member, Membership, MembershipPlan], }
export const scanQrCodeForMemberValidation: ScanQrCodeForMemberValidation<{}, { success: boolean, data?: any }> = async (req, res, context) => {

const { body } = req;

const validationResult = validateMamberSchema.safeParse(body);

if (validationResult.success) {

const { gymSlug, email } = validationResult.data;

const member = await context.entities.Member.findFirst({ where: { email } });

// Notify the gym's display
notifyGym({ gymSlug, data: member });

} else if (validationResult.success === false) {
res.status(400).send({ success: false, data: validationResult.error.errors });
}

res.send({ success: true });
};
export const scanQrCodeForMemberValidation: ScanQrCodeForMemberValidation<{}, { success: boolean, data?: any }> = async (req, res, context) => {

const { body } = req;

const validationResult = validateMamberSchema.safeParse(body);

if (validationResult.success) {

const { gymSlug, email } = validationResult.data;

const member = await context.entities.Member.findFirst({ where: { email } });

// Notify the gym's display
notifyGym({ gymSlug, data: member });

} else if (validationResult.success === false) {
res.status(400).send({ success: false, data: validationResult.error.errors });
}

res.send({ success: true });
};
kapa.ai
kapa.ai4w ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- Based on the API declaration and implementation you've provided, it seems you're working with a custom API endpoint in Wasp. To ensure CORS works correctly for this specific API, you'll need to configure it properly. Here's how you can do that: 1. First, in your main.wasp file, add an apiNamespace declaration:
apiNamespace memberValidation {
middlewareConfigFn: import { apiMiddleware } from "@src/apis",
path: "/api"
}
apiNamespace memberValidation {
middlewareConfigFn: import { apiMiddleware } from "@src/apis",
path: "/api"
}
2. Then, create or update your src/apis.js (or src/apis.ts if you're using TypeScript) file:
import cors from 'cors'
import { config } from 'wasp/server'

export const apiMiddleware = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: config.frontendUrl,
credentials: true,
methods: ['POST', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}))
return middlewareConfig
}
import cors from 'cors'
import { config } from 'wasp/server'

export const apiMiddleware = (middlewareConfig) => {
middlewareConfig.set('cors', cors({
origin: config.frontendUrl,
credentials: true,
methods: ['POST', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}))
return middlewareConfig
}
This configuration will apply CORS settings specifically to your /api routes, including your scanQrCodeForMemberValidation endpoint. If you're still experiencing CORS issues after applying these changes, you might need to ensure that the OPTIONS preflight request is handled correctly. You can do this by modifying your API implementation to handle the OPTIONS method:
export const scanQrCodeForMemberValidation: ScanQrCodeForMemberValidation<{}, { success: boolean, data?: any }> = async (req, res, context) => {
// Handle OPTIONS request for CORS preflight
if (req.method === 'OPTIONS') {
return res.status(200).end();
}

// Your existing code here...
};
export const scanQrCodeForMemberValidation: ScanQrCodeForMemberValidation<{}, { success: boolean, data?: any }> = async (req, res, context) => {
// Handle OPTIONS request for CORS preflight
if (req.method === 'OPTIONS') {
return res.status(200).end();
}

// Your existing code here...
};
Remember, CORS needs to be configured on the server side, which is what we're doing here. The client-side (browser) will automatically handle the CORS protocol based on the headers sent by the server. If you're still facing issues after implementing these solutions, it would be helpful to see the exact error messages you're getting in the browser console. Also, make sure your client-side code is sending the request to the correct URL (including the /api prefix). Wasp Docs: Making Sure CORS Works for APIs (https://wasp-lang.dev/docs/advanced/apis#making-sure-cors-works) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Stefan Vitória, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Filip
Filip4w ago
Hey @Stefan Vitória, I responded in the other thread

Did you find this page helpful?