diff --git a/cors-proxy/index.mjs b/cors-proxy/index.mjs index a7242e39..0a7cf758 100644 --- a/cors-proxy/index.mjs +++ b/cors-proxy/index.mjs @@ -1,49 +1,44 @@ -import https from 'node:https'; import process from 'node:process'; export const handler = async (event) => { const targetUrl = process.env.PROXY_TARGET_URL; - const postData = event.body; - - const options = { + const response = await fetch(targetUrl, { method: 'POST', + body: event.body, headers: { - 'Content-Type': 'application/x-www-form-urlencoded', + 'Content-type': 'application/x-www-form-urlencoded', }, - }; - - return new Promise((resolve, _reject) => { - const req = https.request(targetUrl, options, (response) => { - let data = ''; - - // Collect response data - response.on('data', (chunk) => (data += chunk)); - - // When the request is complete - response.on('end', () => { - resolve({ - statusCode: 200, - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - status: response.statusCode, - headers: response.headers, - body: data, - }), - }); - }); - }); - - req.on('error', (error) => { - resolve({ - statusCode: 500, - body: JSON.stringify({ message: 'Error in request', error: error.message }), - }); - }); + mode: 'no-cors', + }); - req.write(postData); - req.end(); + if (response.status >= 200 && response.status < 300) { + return { + statusCode: 200, + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + status: response.status, + body: await response.text(), + }), + }; + } + + console.error('Received an error response', { + statusCode: response.status, + message: response.message, + headers: response.headers, }); + + return { + statusCode: 400, + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + error: 'Failed to submit form', + status: response.status, + }), + }; }; diff --git a/cors-proxy/serverless.yaml b/cors-proxy/serverless.yaml index cad013c2..d0b32031 100644 --- a/cors-proxy/serverless.yaml +++ b/cors-proxy/serverless.yaml @@ -7,7 +7,7 @@ provider: runtime: nodejs20.x functions: - proxy: + cors-proxy: handler: index.handler events: - http: