🎨 Updates how headers are applied to Netlify CORS proxy

This commit is contained in:
Alicia Sykes 2022-01-01 00:42:55 +00:00
parent 661b1aab07
commit 6e310628f7
1 changed files with 26 additions and 20 deletions

View File

@ -2,41 +2,47 @@
const axios = require('axios'); const axios = require('axios');
exports.handler = (event, context, callback) => { exports.handler = (event, context, callback) => {
// Get URL from header or GET param // Get input data
const requestUrl = event.queryStringParameters.url const { body, headers, queryStringParameters } = event;
|| event.headers['Target-URL']
|| event.headers['target-url'];
// If URL missing, return error // Get URL from header or GET param
if (!requestUrl) { const requestUrl = queryStringParameters.url || headers['Target-URL'] || headers['target-url'];
const returnError = (msg, error) => {
callback(null, { callback(null, {
statusCode: 400, statusCode: 400,
body: JSON.stringify({ success: false, msg: 'Missing Target-URL header' }), body: JSON.stringify({ success: false, msg, error }),
}); });
};
// If URL missing, return error
if (!requestUrl) {
returnError('Missing Target-URL header', null);
} }
let custom = {};
try {
custom = JSON.parse(headers.CustomHeaders || headers.customheaders || '{}');
} catch (e) { returnError('Unable to parse custom headers'); }
// Response headers
const requestHeaders = {
'Access-Control-Allow-Origin': '*',
...custom,
};
// Prepare request // Prepare request
const requestConfig = { const requestConfig = {
method: 'GET', method: 'GET',
url: requestUrl, url: requestUrl,
json: event.body, json: body,
}; headers: requestHeaders,
// Response headers
const headers = {
'Access-Control-Allow-Origin': '*',
...event.headers,
}; };
// Make request // Make request
axios.request(requestConfig) axios.request(requestConfig)
.then((response) => { .then((response) => {
const body = JSON.stringify(response.data); callback(null, { statusCode: 200, body: JSON.stringify(response.data) });
callback(null, { statusCode: 200, body, headers });
}).catch((error) => { }).catch((error) => {
callback(null, { returnError('Request failed', error);
statusCode: 400,
body: JSON.stringify({ success: false, msg: 'Request failed', error }),
});
}); });
}; };