Node js request npm return from callback - node.js

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'
}
})
}`

Related

Axios bad request status 400

I'm having this issue AxiosError: Request failed with status code 400
I checked the console and I test manually the url and It worked, so I don't know what's wrong, this code:
//file controller.js
//Set Create Session
exports.setSession = async (req, res) => {
const data = await request({
path: process.env.APP_LOCALHOST_URL + urlLogin.setCreateSession,
method: 'POST',
body: JSON.stringify(req.body)
});
return res.json(data);
}
//file request.js
exports.request = async ({path, method = "GET", body }) => {
try {
const response = await axios({
method: method,
url: path,
headers: {
'Content-Type': 'application/json'
},
body: body
});
return response;
} catch (error) {
console.log("error: ", error);
}
}
the function setSession is to call in my routes file, and the function request is my reusable component. My intention is to use the function request in many functions, these could be of the GET, DELETE, PUT, POST, PATCH type.
So, currently I get this on console:
data: {
error: '5',
errorId: 'badRequest',
errorString: 'Internal error: Undefined JSON value.'
}

AutoDesk forge viewer Api integration issue

I am integrating Forge Api in my NodeJs application.
All other Api works e.g authentication , creating bucket and translation a model.When I redirect to the html page to view my model it gives the 404 error..I have been stuck on this.
Below is the code and images attached.Authentication and bucket creation Api's skipped in the below code..
Folder structure is
->server
-->app.js
-->viewer.html
App.js
app.post('/api/forge/datamanagement/bucket/upload/uploads/:filename', function (req, res) {
console.log(req.params.filename);
console.log("Token",access_token)
var fs = require('fs'); // Node.js File system for reading files
fs.readFile(`./uploads/${req.params.filename}`, function (err, filecontent) {
console.log(filecontent)
Axios({
method: 'PUT',
url: 'https://developer.api.autodesk.com/oss/v2/buckets/' + encodeURIComponent(bucketKey) + '/objects/' + encodeURIComponent(req.params.filename),
headers: {
Authorization: 'Bearer ' + access_token,
'Content-Disposition': req.params.filename,
'Content-Length': filecontent.length
},
data: filecontent
}).then(function (response) {
// Success
console.log(response);
console.log("IdUrn ====>>>>>>>"+ response.data.objectId)
var urn = response.data.objectId.toBase64();
console.log("In Response")
res.redirect('/api/forge/modelderivative/' + urn);
}).catch(function (error) {
// Failed
console.log(error.message);
res.send(error.message);
});
});
});
app.get('/api/forge/modelderivative/:urn', function (req, res) {
console.log("urrrr",req.params.urn)
var urn = req.params.urn;
var format_type = 'svf';
var format_views = ['2d', '3d'];
Axios({
method: 'POST',
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/job',
headers: {
'content-type': 'application/json',
Authorization: 'Bearer ' + access_token
},
data: JSON.stringify({
'input': {
'urn': urn
},
'output': {
'formats': [
{
'type': format_type,
'views': format_views
}
]
}
})
})
.then(function (response) {
// Success
console.log("Translated=============>>>",response);
res.redirect('/viewer.html?urn=' + urn);
})
.catch(function (error) {
// Failed
console.log(error);
// res.send(error.message);
});
});
Response in the network Tab

Always get 502 error when calling AWS lambda endpoint from Node Js using `requestjs`

trying to post data in our AWS serverless api using Nodejs Request package but always get 502 error and can post data from the front end app (React or Jquery).
var dataToPost = {
name: 'ABC',
address: 'XYZ'
}
request(
{ method: 'POST'
, uri: 'url here...'
, headers: {
'User-Agent': 'request'
} , multipart:
[ { 'content-type': 'application/json'
, body: JSON.stringify(dataToPost)
}
]
}
, function (error, response, body) {
if(response.statusCode == 201){
console.log('document saved')
} else {
console.log('error: '+ response.statusCode)
console.log(body)
}
}
)```
If you are able to post data using react and Jquery then probably you are not making a post request correctly.Try this code for post request :
const request = require('request');
var dataToPost = {
name: 'ABC',
address: 'XYZ'
}
const options = {
url: 'url goes here',
json: true,
body: dataToPost
};
request.post(options, (err, res, body) => {
if (err) {
return console.log(err);
}
console.log(`Status: ${res.statusCode}`);
console.log(body);
});
Alternatively you can also use axios which makes code more readable and have inbuilt promise support:
const axios = require('axios');
var dataToPost = {
name: 'ABC',
address: 'XYZ'
}
const url = 'put url here'
axios.post(url, data)
.then((res) => {
console.log(`Status: ${res.status}`);
console.log('Body: ', res.data);
}).catch((err) => {
console.error(err);
});
Also check what does AWS Lmbada logs says.

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;
}
}

nodejs try catch and res.status usage

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.

Resources