AutoDesk forge viewer Api integration issue - node.js

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

Related

Axios and POST request to Zendesk API

I'm trying a custom ticket form with the Zendesk API for end users. I followed this tutorial but it uses Python whereas I use Node and React. I use Axios but I got an error response
data: { error: "Couldn't authenticate you" }
Here is my code
var axios = require('axios');
var config = {
method: 'post',
url:'https://subdomain.zendesk.com/api/v2/requests.json',
headers: {
'content-type': 'application/json'
},
data:{'request':{'subject': 'test', 'comment': {'body': 'ceci est un test'}}},
auth:('MY_EMAIL/token:_TOKEN'),
};
axios(config)
.then(function (response) {
res.send(response.data);
})
.catch(function (error) {
console.log(error);
});
You should set your token as header like so:
var axios = require('axios');
const token = '{base-64-encoded email_address/token:api_token}'
var config = {
method: 'post',
url:'https://subdomain.zendesk.com/api/v2/requests.json',
headers: {
'content-type': 'application/json',
'Authorization': `Basic ${token}`
},
data:{'request':{'subject': 'test', 'comment': {'body': 'ceci est un test'}}}
};
axios(config)
.then(function (response) {
res.send(response.data);
})
.catch(function (error) {
console.log(error);
});

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

Node.js 3rd party REST API call

Im using nodejs to make a call to a 3rd party API. My code code returns the correct data for an id that I'm passing in my backend. When I run my app, to retrieve the data I go to localhost:5000/api/Dls.
My code
app.get("/api/Dls", (req, res) => {
const response = {
success: false
};
if (req.user && Authorized.myToken) {
response.success = true;
response.data = {};
response.data.user = req.user;
const id = response.data.user.sub;
var options = {
method: 'GET',
url: 'https://someApi/byId/' + 'id',
headers:
{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};
request(options, function (error, response, body){
if (error) {
console.log(error);
return;
}
const data = response.body;
const userDls = JSON.parse(data)
return res.json(userDls);
});
}
});
Now I'm trying to do something like this localhost:5000/api/Dls/1234 instead of using a hard coded id in the backend
I attempted doing the following but when I enter a valid id in the url (ex. localhost:5000/api/Dls/1234) I get this "", any idea to what I should be doing?
app.get("/api/Dls/:id", (req, res) => {
const response = {
success: false
};
if (Authorized.myToken) {
response.success = true;
var options = {
method: 'GET',
url: 'https://someApi/byId/',
headers:
{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};
request(options, function (error, response, body){
if (error) {
console.log(error);
return;
}
const data = response.body;
const userDls = JSON.parse(data)
return res.json(userDls);
});
}
});
Any feedback would be appreciated!
You are not passing the route id to the api.
response.success = true;
var options = {
method: 'GET',
url: 'https://someApi/byId/' + req.params.id,
headers:{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};

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.

HTTP Module to Request Module Translation

How to rewrite this node.js code, just using the request module not http module?
var options = {
url: 'https://dnxr7vm27d.execute-api.us-east-1.amazonaws.com/prod/GetRewardInfo',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'kE2xi2OgUa7jfijmsd0jQ74aJntJwUEW2EU8LUsi'
}
};
var req = http.request(options, function(res) {
console.log('Status:' + res.statusCode);
console.log('Headers: ' + JSON.stringify(res.headers));
res.on('data', function(body) {
console.log('Body:' + body);
});
});
req.write('{"x-api-key":"12345", "Content-Type":"application/json", "appId":"DEMO1","momentId":"GAME_COMPLETE","deviceType":'
Android ','
campaignId ':"DEMOCAMP1","rewardGroupId":"amz1yprime"}');
req.end();
I've done part of it:
const request = require('request');
const data = JSON.stringify({
"appId": "DEMO1",
"momentId": "GAME_COMPLETE",
"deviceType": 'Android ',
'campaignId ': "DEMOCAMP1",
"rewardGroupId": "amz1yprime"
})
const options = {
url: 'https://dnxr7vm27d.execute-api.us-east-1.amazonaws.com/prod/GetReward',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'kE2xi2OgUa7jfijmsd0jQ74aJntJwUEW2EU8LUsi'
},
};
request.post(options, function(err, res, body) {
console.log(body);
});
But i don't know how to send "data" and how to get a response to the request
The re-write is not drastic. It's some few simple change.
const request = require('request')
var options = {
url: 'https://dnxr7vm27d.execute-api.us-east-1.amazonaws.com/prod/GetRewardInfo',
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'x-api-key': 'kE2xi2OgUa7jfijmsd0jQ74aJntJwUEW2EU8LUsi'
},
body: {
'appId': 'DEMO1',
'momentId':'GAME_COMPLETE',
'deviceType' : 'Android',
'campaignId' : 'DEMOCAMP1',
'rewardGroupId': 'amz1yprime'
},
json: true // sets body to JSON representation of value
};
request.post(options, (err, httpResponse, body) => {
if (err) console.error(err);
// httpResponse contains the full response object, httpResponse.statusCode etc
else console.log(body);
})

Resources