Skip to content

Commit

Permalink
proxy fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Precious-Macaulay authored Nov 11, 2024
1 parent 74f6a42 commit 615a7c0
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
22 changes: 17 additions & 5 deletions api/proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
}
}
19 changes: 19 additions & 0 deletions vercel.json
Original file line number Diff line number Diff line change
@@ -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"
}
]
}

0 comments on commit 615a7c0

Please sign in to comment.