From 615a7c0c0cac596d4041cdc9d69cfb5740641de0 Mon Sep 17 00:00:00 2001 From: Macaulay Precious Date: Mon, 11 Nov 2024 07:09:11 +0100 Subject: [PATCH] proxy fix --- api/proxy.js | 22 +++++++++++++++++----- vercel.json | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) create mode 100644 vercel.json diff --git a/api/proxy.js b/api/proxy.js index 56d12fa..07e6622 100644 --- a/api/proxy.js +++ b/api/proxy.js @@ -6,19 +6,31 @@ dotenv.config(); const proxy = httpProxy.createProxyServer({}); const BEARER_TOKEN = process.env.ASTRIA_API_KEY; -export default function handler(req, res) { +const allowedMethods = ['GET', 'POST', 'OPTIONS', 'DELETE']; + +export default async function handler(req, res) { + // Handle CORS headers res.setHeader('Access-Control-Allow-Origin', '*'); - res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, DELETE'); + res.setHeader('Access-Control-Allow-Methods', allowedMethods.join(', ')); res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type'); + // Handle preflight OPTIONS request if (req.method === 'OPTIONS') { return res.status(204).end(); } + // Ensure the Authorization header is set correctly req.headers['Authorization'] = `Bearer ${BEARER_TOKEN}`; - proxy.web(req, res, { target: 'https://api.astria.ai', changeOrigin: true }, (error) => { + // Modify the target API URL to include the path from the request URL + const targetUrl = `https://api.astria.ai${req.url.replace('/api/proxy', '')}`; + + // Proxy the request to the target API + try { + proxy.web(req, res, { target: targetUrl, changeOrigin: true }); + } catch (error) { console.error('Proxy error:', error); - res.status(500).end('Proxy error occurred.'); - }); + // Sending a more detailed error message + res.status(500).json({ error: 'Failed to proxy request', details: error.message }); + } } diff --git a/vercel.json b/vercel.json new file mode 100644 index 0000000..9ab06ac --- /dev/null +++ b/vercel.json @@ -0,0 +1,19 @@ +{ + "functions": { + "api/proxy.js": { + "memory": 3009, + "maxDuration": 30 + } + }, + "routes": [ + { + "src": "/api/proxy(?:/.*)?", + "dest": "/api/proxy.js" + }, + { + "src": "/rails/active_storage/blobs/redirect(?:/.*)?", + "dest": "/api/proxy.js" + } + ] + } + \ No newline at end of file