Skip to content

Instantly share code, notes, and snippets.

@juanbrusco
Created June 27, 2022 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanbrusco/94903612c7da049151d8c63e2bda1beb to your computer and use it in GitHub Desktop.
Save juanbrusco/94903612c7da049151d8c63e2bda1beb to your computer and use it in GitHub Desktop.
NodeJS fetch handling body
router.post('/endpointname', async function (req, res, next) {
let bodyObj = { "x": {} };
let requestURL = "https://reqres.in/api/register";
let requestOptions = {
method: "POST",
body: JSON.stringify(bodyObj),
headers: { 'Content-Type': 'application/json' }
};
try {
const urlResponse = await fetch(requestURL, requestOptions);
const responseBody = await urlResponse.text();
checkStatus(urlResponse, responseBody);
res.send(responseBody);
} catch (err) {
returnErrorResponse(res, err, "endpointname");
}
});
var checkStatus = function (urlResponse, responseBody) {
if (!urlResponse.ok) {
const errorResponse = {
statusText: urlResponse.statusText,
status: urlResponse.status,
body: responseBody,
};
throw errorResponse;
}
return urlResponse;
}
var returnErrorResponse = function (res, err, id) {
const status = err.status ? err.status : 500;
const errorCatch = err.message ? err.message : null;
const errorResponse = err.statusText ? JSON.stringify(err) : JSON.stringify(err);
_logger.error(`ERROR: pipeline-ingestion.js ${id}`);
_logger.error(`ERROR: ${status}-${errorCatch ? errorCatch : errorResponse}`);
return res.status(status).send({
message: `ERROR: pipeline-ingestion.js ${id}`,
err: errorCatch ? errorCatch : errorResponse
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment