I’m facing a persistent CORS issue when trying to make a POST request from my frontend application to an API deployed with the Serverless Framework. My frontend is running on localhost:5173 (dev server) and the backend API endpoint is at https://zgrciu0uce.execute-api.us-east-1.amazonaws.com/dev/auth/createUserFromAdmin.
Error from the browser’s console
Access to XMLHttpRequest at 'https://zgrciu0uce.execute-api.us-east-1.amazonaws.com/dev/auth/createUserFromAdmin' from origin 'http://localhost:5173' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
POST https://zgrciu0uce.execute-api.us-east-1.amazonaws.com/dev/auth/createUserFromAdmin net::ERR_FAILED
In serverless.yml, I added CORS configuration like this (I’ve just followed official docs):
functions:
authCreateUserFromAdminHandler:
handler: src/modules/Auth/handlers/createUserFromAdminHandler.handler
events:
- http:
path: auth/createUserFromAdmin
method: post
cors: true
In lambda function authCreateUserFromAdminHandler’s code:
export const handler = async (event: APIGatewayEvent, context: Context, callback: Function) => {
/* ... process information */
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true
}
const response = {
statusCode: 201,
headers,
body: JSON.stringify({ OK: true })
}
}
And in my frontend I run requests with Axios. Axios is configured this way:
import axios from 'axios'
import { useAuthStore } from '@/stores/authStore';
const authStore = useAuthStore();
const api = axios.create({
baseURL: 'https://zgrciu0uce.execute-api.us-east-1.amazonaws.com/dev',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Authorization': `${authStore.tokenType} ${authStore.accessToken}`
},
});
export { api }
Then in my .vue components, I just use the axios exported before:
import { api } from '@/libs/axios'
await api.post('/auth/createUserFromAdmin', newUser) // this line throws the error (see beginning of this post).
I wonder how could I fix this?