nodejs try catch and res.status usage - node.js

i am still not so happy about my code in regards to structuring of try/catch and res.status.
I guess the catch block will never reached when an error within the request is coming back as response right ?
What is the best way to structure this, i am only interested in giving back the correct res.status in regards to the occuring error ??
setPublicLink: async (req, res, next) => {
try{
console.log('Entering setPublicLink');
var mytoken = "Bearer "+process.env.MY_TOKEN;
request({
url: ' https://content.dropboxapi.com/2/files/upload',
headers: {
'content-type' : 'application/octet-stream',
'authorization' : mytoken
},
encoding: null,
method: 'POST',
body: fs.createReadStream(fileItem.path),
encoding: null
}, (error, response, body) => {
if (error) {
console.log(error);
console.log(response);
//return res.status(401).json({error: 'Upload of file was not successful.'});
} else if ( response.statusCode == 200) {
//nothing to do
} else {
console.log(response);
return res.status(401).json({error: 'Upload of file was not successful.'});
}
});
request({
url: 'https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings',
headers: {
'content-type' : 'application/json',
'authorization' : mytoken
},
method: 'POST',
body: JSON.stringify(reqBodyJson)
}, (error, response, body) => {
if (error) {
console.log(error);
console.log(response);
return res.status(401).json({error: 'Error when trying to set public link'});
} else if ( response.statusCode == 200) {
return res.status(200).json({success: 'Public Link has been set successfully.'});
} else if ( response.statusCode == 409) {
return res.status(409).json({error: 'Nothing to set. Public link already exists.'});
} else {
return res.status(401).json({error: 'Could not set public link'});
}
});
}
catch (err) {
console.log('Error Occured : '+ err);
return res.status(401).json({error: 'Error occured trying to set publicLink'});
}
},

your code will never hit the catch block since your handling all off the errors. but your code style is difficult to maintain it is better to use promises for example you could use request-promise module then your code will be somthing like if you have node 8+:
setPublicLink: async (req, res, next) => {
try{
console.log('Entering setPublicLink');
var mytoken = "Bearer "+process.env.MY_TOKEN;
var response = await requestPromise({
url: ' https://content.dropboxapi.com/2/files/upload',
headers: {
'content-type' : 'application/octet-stream',
'authorization' : mytoken
},
encoding: null,
method: 'POST',
body: fs.createReadStream(fileItem.path),
encoding: null
});
var response1 = await requestPromise({
url:
'https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings',
headers: {
'content-type' : 'application/json',
'authorization' : mytoken
},
method: 'POST',
body: JSON.stringify(reqBodyJson)
});
res.send({success: 'Public Link has been set successfully.'});// it sends 200 automatically
}
catch(ex){
res.sendStatus(401);
}
}
also you can get the response headers.

Related

How to send a post request on Typescript?

I have this code but I need to translate it to Typescript, and having issues finding the request module
function sendNotificationToUser(username, message, onSuccess) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key='+API_KEY
},
body: JSON.stringify({
notification: {
title: message
},
to : '/topics/user_'+username
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
else {
onSuccess();
}
});
}
const response = await fetch("https://fcm.googleapis.com/fcm/send", {
method: 'POST',
body: JSON.stringify({notification: {title: message},to : '/topics/user_'+username}),
headers: {'Content-Type': 'application/json', 'Authorization': 'key='+API_KEY}
});
if (!response.ok)
{
console.error("Error");
}
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
else{
onSuccess();
}

Node js request npm return from callback

I'm suffering to create a server requesting to external server.
What I'm planning to do here is, sending a request to external server and return a code(like success or fail) to the client. But the callback function doesn't return. How should I make this happen?
app.post('/request', (req, res) =>{
const value = 'blah blah cyka'
const uploadValue = uploadTo(value)
res.json(uploadValue)
return
}
// This is request function
function uploadTo(VALUE){
await request.post({
url: 'https://stackunderpants.com/api',
method: 'POST',
rejectUnauthorized: false,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(VALUE)
}, (err, response, body) =>{
if(err){
console.log(response)
console.log(body)
console.log('Error has been occurred while sending to server. \n', err)
return {
'code': '400',
'detail': 'Error has been occurred while sending to server'
}
}
return {
'code': '200'
}
})
}
I've tried await async but not working...
const uploadValue = await uploadTo(value)
I'm literally dying right now.. it has been a week since I got this
Just edit your 3 lines code:
add "async" in app.post('/request', async (req, res) =>{...
add "await" in const uploadValue = await uploadTo(value) ...
add "await" in async function uploadTo(VALUE){ ....
`app.post('/request', async (req, res) =>{
const value = 'blah blah cyka'
const uploadValue = await uploadTo(value)
res.json(uploadValue)
return
}`
// This is request function
`async function uploadTo(VALUE){
await request.post({
url: 'https://stackunderpants.com/api',
method: 'POST',
rejectUnauthorized: false,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(VALUE)
}, (err, response, body) =>{
if(err){
console.log(response)
console.log(body)
console.log('Error has been occurred while sending to server. \n', err)
return {
'code': '400',
'detail': 'Error has been occurred while sending to server'
}
}
return {
'code': '200'
}
})
}`

make a post request with a body in nodejs

I am using nodeJS to communicate with an API.
To do that, I am using a post request.
In my code, I use form data to pass the variables, but I get error 400. When I try to put body instead, I get an error saying that my variables are undefined.
This is the API: https://developer.hpe.com/api/simplivity/endpoint?&path=%2Fdatastores
My request:
async function postCreateDatastore(url, username, password, name, clusterID, policyID, size, token) {
console.log (name, clusterID, policyID, size)
var options = {
method: 'POST',
url: url + '/datastores',
headers: {
'Content-Type': 'application/vnd.simplivity.v1.1+json',
'Authorization': 'Bearer ' + token,
},
formdata:
{
name: name,
omnistack_cluster_id: clusterID,
policy_id: policyID,
size: size,
}
};
return new Promise(function (resolve, reject) {
request(options, function (error, response, body) {
if (response.statusCode === 415) {
console.log(body);
resolve(body);
} else {
console.log("passed");
console.log(JSON.parse(body));
resolve(response.statusCode);
}
});
});
}
the answer:
testsimon20K 4a298cf0-ff06-431a-9c86-d8f9947ba0ba ea860974-9152-4884-a607-861222b8da4d 20000
passed
{ exception:
'org.springframework.http.converter.HttpMessageNotReadableException',
path: '/api/datastores',
message:
'Required request body is missing: public org.springframework.http.ResponseEntity<java.lang.Object> com.simplivity.restapi.v1.controller.DatastoreController.createDatastore(javax.servlet.http.HttpServletRequest,com.simplivity.restapi.v1.mo.actions.CreateDatastoreMO) throws org.apache.thrift.TException,org.springframework.web.HttpMediaTypeNotSupportedException,com.simplivity.restapi.exceptions.ObjectNotFoundException,java.text.ParseException,java.io.IOException,com.simplivity.util.exceptions.ThriftConnectorException,com.simplivity.common.exceptions.DataSourceException',
timestamp: '2019-07-04T08:51:49Z',
status: '400' }
thank you for your help!
I advice to use node-fetch to post your data. This package let you use the default fetch function from ES6.
Here is your answer:
//require the node-fetch function
const fetch = require('node-fetch');
async function postCreateDatastore(url, username, password, name, clusterID, policyID, size, token) {
console.log(name, clusterID, policyID, size);
try {
const response = await fetch(`${url}/datastores`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
},
body: JSON.stringify({
name,
omnistack_cluster_id: clusterID,
policy_id: policyID,
size
})
});
const json = await response.json();
console.log(json);
return json;
}
catch(e) {
throw e;
}
}

POST Requests not working using request module in node.js

I want to send data to the java back end which is run on tomcat server.this is what i have tried so far.i have already installed request module.get method is working properly.
Router.post('/', function(req, res) {
request({
uri: "http://localhost:8080/HIS_API/rest/UserService/registerUser",
method: "POST",
form: {
roleId:2,
employeeId:26,
userName:"testing",
password:"123"
}
}, function(error, response, body) {
console.log(body);
});
});
You have to use JSON.stringify to send data like in this format. before that write console.log(error). and check what's the error you are getting.
request({
url: url, //URL to hit
method: 'post',
headers: { "Authorization": req.headers.authorization},//if required
timeout: 60 * 1000,
body: JSON.stringify(body)
}, function (error, result, body) {
if (error) {
console.log(error);
} else if (result.statusCode === 500) {
console.log('error');
} else {
console.log(body);
}
});

Testing Auth0 API Patch Request

Trying to test Auth0 API patch request to modify user_metadata.
Using mocha and superagent for testing.
Get succeeds, but doing a patch with a userid and sending
.send({ "metadata": { "nickname": "Jill" } })
in the mocha testing file does not work.
router.patch('/:id', function(req, res, next) {
var options = {
method: 'PATCH',
url: 'https://mrides.auth0.com/api/v2/users/' + req.params.id,
headers: {
Authorization: "Bearer " + apiToken
},
data: req.body
}
request.patch(options, function(err, response, body) {
if(!err && response.statusCode == 200) {
res.send(JSON.parse(body))
} else {
res.status(500).send(err);
}
})
});
Error:
{
"statusCode": 400,
"error": "Bad Request",
"message": "Payload validation error: 'Expected type object but found type null'.",
"errorCode": "invalid_body"
}
Had seen this question:
Auth0 API Request
but it did not work when trying:
data: JSON.stringify(req.body)
Any help or links on how to propery modify user_metadata?
Have also been looking through Auth0 docs but no advancement yet.
change options following way:
var options = {
method: 'PATCH',
url: 'https://mrides.auth0.com/api/v2/users/' + req.params.id,
headers: {
Authorization: "Bearer " + apiToken
},
// change here
body: req.body
}
request.patch(options, function(err, response, body) {
if(!err && response.statusCode == 200) {
res.send(JSON.parse(body))
} else {
res.status(500).send(err);
}
})
};

Resources