Created
June 27, 2022 21:30
-
-
Save juanbrusco/94903612c7da049151d8c63e2bda1beb to your computer and use it in GitHub Desktop.
NodeJS fetch handling body
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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