Skip to content

Commit

Permalink
Fixed cors headers (#27)
Browse files Browse the repository at this point in the history
* fixed cors headers
  • Loading branch information
rake7h authored Dec 5, 2023
1 parent 2e357a1 commit 11893dd
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions src/pages/api/moxy/[...endpoint].ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const body = req.body;

// 1. get the endpoint from url by removing /moxy prefix
const {pathname, params} = getEndpointPathFromURL({ url: req.url || '' })
const { pathname, params } = getEndpointPathFromURL({ url: req.url || '' })

// 2. get the endpoint details from db
const { id, moxyType, proxyDetails, mockDetails } = await matchEndpointPathToDB({ pathname: pathname })
Expand All @@ -19,25 +19,28 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
// 3. if exist check is a proxy or mock
// if proxy do a proxy
if (moxyType === 'proxy') {

// set moxy-type identifiers
res.setHeader('x-moxy-type', 'proxy');

try {
const axiosRes = await makeProxyRequest({
headers: req.headers,
method: req.method,
targetHost: proxyDetails.targetHost,
endpointPath: pathname,
data: body ? JSON.stringify(body): undefined,
data: body ? JSON.stringify(body) : undefined,
params
});

// Set the target response headers to the proxy response
Object.keys(axiosRes.headers).forEach((key) => {
res.setHeader(key, axiosRes.headers[key]);
});

// set moxy-type identifiers
res.setHeader('x-moxy-type', 'proxy');

// Set/Overwrite CORS allow headers
res.setHeader("Access-Control-Allow-Origin", "*")
res.setHeader("Access-Control-Allow-Methods", 'GET, POST, PUT, DELETE, OPTIONS')
res.setHeader("Access-Control-Allow-Headers", "*")

// Send the response from the target to the client
return res.status(axiosRes.status).send(axiosRes.data);
}
Expand All @@ -54,7 +57,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {

// 4. if mock, read the collection for endpoint and return
if (moxyType === "mock") {

// set moxy-type identifiers
res.setHeader('x-moxy-type', `mock, ${mockDetails.collectionId}`);

Expand Down

0 comments on commit 11893dd

Please sign in to comment.