2022-01-01 01:23:39 +03:00
|
|
|
/* A Netlify cloud function to handle requests to CORS-disabled services */
|
|
|
|
const axios = require('axios');
|
|
|
|
|
|
|
|
exports.handler = (event, context, callback) => {
|
2022-01-01 03:42:55 +03:00
|
|
|
// Get input data
|
|
|
|
const { body, headers, queryStringParameters } = event;
|
|
|
|
|
2022-01-01 01:23:39 +03:00
|
|
|
// Get URL from header or GET param
|
2022-01-01 03:42:55 +03:00
|
|
|
const requestUrl = queryStringParameters.url || headers['Target-URL'] || headers['target-url'];
|
2022-01-01 01:23:39 +03:00
|
|
|
|
2022-01-01 03:42:55 +03:00
|
|
|
const returnError = (msg, error) => {
|
2022-01-01 01:23:39 +03:00
|
|
|
callback(null, {
|
|
|
|
statusCode: 400,
|
2022-01-01 03:42:55 +03:00
|
|
|
body: JSON.stringify({ success: false, msg, error }),
|
2022-01-01 01:23:39 +03:00
|
|
|
});
|
2022-01-01 03:42:55 +03:00
|
|
|
};
|
|
|
|
// If URL missing, return error
|
|
|
|
if (!requestUrl) {
|
|
|
|
returnError('Missing Target-URL header', null);
|
2022-01-01 01:23:39 +03:00
|
|
|
}
|
|
|
|
|
2022-01-01 03:42:55 +03:00
|
|
|
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,
|
|
|
|
};
|
|
|
|
|
2022-01-01 01:23:39 +03:00
|
|
|
// Prepare request
|
|
|
|
const requestConfig = {
|
|
|
|
method: 'GET',
|
|
|
|
url: requestUrl,
|
2022-01-01 03:42:55 +03:00
|
|
|
json: body,
|
|
|
|
headers: requestHeaders,
|
2022-01-01 01:23:39 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
// Make request
|
|
|
|
axios.request(requestConfig)
|
|
|
|
.then((response) => {
|
2022-01-01 03:42:55 +03:00
|
|
|
callback(null, { statusCode: 200, body: JSON.stringify(response.data) });
|
2022-01-01 01:23:39 +03:00
|
|
|
}).catch((error) => {
|
2022-01-01 03:42:55 +03:00
|
|
|
returnError('Request failed', error);
|
2022-01-01 01:23:39 +03:00
|
|
|
});
|
|
|
|
};
|