How to properly use putAsync - node.js

I searched here and there and ended up with no finding regarding putAsync method of promisified request by bluebird.
var request = require('request');
var Promise = require('bluebird');
Promise.promisifyAll(require("request"));
request.putAsync({
uri: buApiUrl,
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
name: BU,
workstations: formattedWorkStaions[BU]
})
}).spread(function (response, body) {
debugHelper.log(body);
}).catch(function (err) {
debugHelper.error(err);
});
Above is the code snippet that is in my program. And it does not send put request. While using postAsync, if will send post request successfully.

Your code seems fine to me.
Example
var request = require('request');
var Promise = require('bluebird');
Promise.promisifyAll(require("request"));
request.putAsync({
uri: 'https://httpbin.org/put',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
name: 'anon'
})
}).spread(function (response, body) {
console.log(body);
}).catch(function (err) {
console.error(err);
});
OR you can just pass JSON body like this -
request.putAsync({
uri: 'https://httpbin.org/put',
json: { name: 'anon' }
})
....
Make sure the API end-point is taking PUT requests and the variables BU,formattedWorkStaions[BU] are properly defined. I guess formattedWorkStaions should be formattedWorkStations?

Related

Search Contacts with SendGrid API

https://sendgrid.api-docs.io/v3.0/contacts/search-contacts
I'm attempting to search for a contact as shown in SendGrids docs above. In the body section below I'd like to change the hard coded "andrew#gmail.com" to be a variable. Such as email = req.user.email; What is the correct way to do that? Just setting the variable and dropping in 'email' does not work.
var request = require("request");
var options = { method: 'POST',
url: 'https://api.sendgrid.com/v3/marketing/contacts/search',
headers:
{ 'content-type': 'application/json',
authorization: 'Bearer SG.key' },
body: { query: 'email LIKE \'andrew#gmail.com\' AND CONTAINS(list_ids, \'6bcc2d0c-ea17-41ba-a4a1-962badsasdas1\')' },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Twilio SendGrid developer evangelist here.
Try using string interpolation using back ticks (which, as an added bonus, means you don't have to escape your single quotes), like below:
const email = req.user.email;
const body = `email LIKE '${email}' AND CONTAINS(list_ids, '6bcc2d0c-ea17-41ba-a4a1-962badsasdas1')`;
const options = {
method: 'POST',
url: 'https://api.sendgrid.com/v3/marketing/contacts/search',
headers: {
'content-type': 'application/json',
authorization: 'Bearer SG.key'
},
body: { query: query },
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});

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

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 request target url

i want to get the result for this target url. by browser the result is ok, but this nodejs code don't work. i wish someone can help me,thanks a lot.
var request = require('request');
request = request.defaults({
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
}
});
request('http://xueqiu.com/stock/search.json?code=alibaba', function(error, res, body) {
if (error) {
console.log(error);
} else {
console.log(res);
}
});
You can get the cookie from xueqiu.com homepage before hitting this URL. Cookies can be reused using a jar
var request = require('request');
request = request.defaults({
headers: {'Accept': '*/*',
'Content-Type': 'application/json'},
jar: true // reuse cookies across requests
});
request('http://xueqiu.com', function() {
request('http://xueqiu.com/stock/search.json?code=alibaba', function(error, res, body) {
if (error) {
console.log(error);
} else {
console.log(res);
}
});
});

Resources