Node NPM Request how to send a post request - node.js

I have been googling for this and only found this.
let req = request({
url: "http://localhost/api/v1/phone",
method: 'POST',
json: {
param1: "abc",
param2: "def"
}
}, function callback(error, response, body) {});
This doesn't work. The error is:
client.js:771 POST http://localhost/[object%20Object] 400 (Bad Request)
How to fix this? This fails with the same eror if I change it to request.post.
let req = request.post({
url: 'http://localhost/api/v1/phone'
}, (error, response, body) =>{
logger.log('test123.error', error);
logger.log('test123.response', response);
logger.log('test123.body', body);
});
but apparently it doesn't work.

Related

node.js + request => response showing junk response

I am using the node.js + request for send HTTP request to URL. I required the JSON response, but I get junk character.
Here is my node.js code
var request = require('request');
var post_data = { UserName: "xxxxx", Password: "xxxxx" };
var post_options = {
url: 'http://xxxxxxx.info/api/CoreUser/cognitoLogin',
method: 'POST',
form: post_data,
headers: {
'AppID': 'zNiphaJww8e4qYEwJ96g555HTAAbAXdj',
'OAuth': 'xxxxxxxxxxxxxxxxxx',
//'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/json;charset=UTF-8',
}
};
// Set up the request
request(post_options, function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
console.log("200");
console.log(response);
}
});
But I received response in junk characters.
I need result in jSON format, What is wrong in this request?
I found the issue, reason is that API response send in gZip format. Here is the change we have to made here. Just enable gzip: true that resolve the things.
var request = require('request');
var post_data = { UserName: "xxxxx", Password: "xxxxx" };
var post_options = {
url: 'http://xxxxxxx.info/api/CoreUser/cognitoLogin',
method: 'POST',
gzip: true,
form: post_data,
headers: {
'AppID': 'zNiphaJww8e4qYEwJ96g555HTAAbAXdj',
'OAuth': 'xxxxxxxxxxxxxxxxxx',
//'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/json;charset=UTF-8',
}
};
// Set up the request
request(post_options, function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
console.log("200");
console.log(response);
}
});
You are missing { json: true } in request call
request(post_options, { json: true }, function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
console.log("200");
console.log(response);
}
});

How to set the timeout for sending requests?

I have a cycle and I need this request to be sent every 3 seconds. How can do that?
request({
url: `http://localhost:port/user/patch/${api.rows[j].id}`,
method: 'POST',
headers: {
'Cookie': cookies
}
},
function (error, response, body) {
console.log('patch:', body)
}).form({
Name: db.rows[i].NAME
})
window.setInterval(function(){
/// call your function here
}, 3000);
Please Try this JS code for send request in every three second
Put the code inside a function and call the function recursively with a timer
function processData(){
let db = ///Get the data from somewhere
db.rows.forEach(row => {
setTimeout(() => myJob(row), 3000)
})
}
function myJob(row){
request({
url: `http://localhost:port/user/patch/${api.rows[j].id}`,
method: 'POST',
headers: {
'Cookie': cookies
}
},
function (error, response, body) {
console.log('patch:', body)
}).form({
Name: row.NAME
})
}

How to upload File to Azure Data Lake through Typescript REST CALLS

My problem was to upload the file from local directory to Azure Data Lake Store using Typescript only. I then found very useful REST API solution, I tested the REST API to perform all the required operations through postman and they worked fine, I then moved to Typescript to make these calls from typescript. Here is link to that: https://learn.microsoft.com/en-us/azure/data-lake-store/data-lake-store-data-operations-rest-api
To make REST CALLS through Typescript I'm using request-promise package, that I installed using npm install request-promise command. The documentation of this package is provided in this link:- https://github.com/request/request
But i'm able to perform all operations of the REST API i.e; Service-to-Service authentication, Creating Folder, Listing Folders, Rename File, Read File and so on. But i am not able to perform two operations/REST CALLS i.e; Upload File and Delete File, every time I make this call it gives Run Time Exception and error code 501 saying that this operation has not been implemented though i have tested these operations through Post Man and they work fine that way.
Is there any Access problem or what?
Here is the code of Typescript:
var fs = require('fs');
var request = require('request-promise');
var accessToken;
getAccessToken();
setTimeout(listFolders, 5000);
setTimeout(renameFile, 5000);
setTimeout(uploadData, 5000);
setTimeout(readData, 5000);
function getAccessToken() {
request(
{
method: 'post',
url: 'https://login.microsoftonline.com/067e9632-ea4c-4ed9-9e6d-
e294956e284b/oauth2/token',
form: {
grant_type: 'client_credentials',
resource: 'https://management.core.windows.net/',
client_id: 'dc9a4034-b03f-4974-9760-99541137a31c',
client_secret: 'mJ1Eba+sz0hXQko7gBN3D5WPDVLySCHXg4Mg5F4Ru4s='
},
json: true,
}, function (error, response, body) {
//Print the Response
accessToken = body.access_token;
console.log(accessToken);
});
}
function uploadData() {
fs.createReadStream('E:/accessToken.txt')
.pipe(request({
method: 'post',
url:
'https://bswadls.azuredatalakestore.net/webhdfs/v1/iModelAnalytics/abc.txt?
op=CREATE',
json: true,
headers: {
"Authorization": "Bearer " + accessToken,
}
},
function (error, response, body) {
console.log(response.status);
}
));
}
function readData() {
request(
{
method: 'GET',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/iModelAnalyti
cs/readFile1.txt?op=OPEN'
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true,
}, function (error, response, body) {
//Print the Response
console.log("\n\nData = "+body);
//console.log(response);
}
);
}
function listFolders() {
request(
{
method: 'GET',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/
iModelAnalytics?op=LISTSTATUS',
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true,
}, function (error, response, body) {
//Print the Response
console.log("************List Folders*****************\n ");
console.log(body);
}
);
}
function deleteFile() {
request(
{
method: 'PUT',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/
iModelAnalytics/readFile.txt?op=DELETE',
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true,
}, function (error, response, body) {
//Print the Response
console.log("***************Delete File*****************\n ");
console.log(body);
console.log('Response= \n');
console.log(response);
}
);
}
function renameFile() {
request(
{
method: 'PUT',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/
iModelAnalytics/readFile1.txt?
op=RENAME&destination=/iModelAnalytics/readFile2.txt',
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true,
}, function (error, response, body) {
//Print the Response
console.log("*************************Delete File*****************\n
");
console.log(body);
console.log('Response= \n');
console.log(response);
}
);
}
This is the error that I get:
Please share any thoughts regarding this.
Thanks a lot in advance.
PUT should be used to upload data whereas DELETE should be used to delete a file.
Append this &write=true to the query string when uploading data via pipe.
Try to change the code to:
function uploadData() {
fs.createReadStream('E:/accessToken.txt').pipe(request({
method: 'put',
url:'https://bswadls.azuredatalakestore.net/webhdfs/v1/iModelAnalytics/abc.txt?op=CREATE&write=true',
json: true,
headers: {
"Authorization": "Bearer " + accessToken,
}
}, function (error, response, body) {
console.log(response.status);
}));
}
function deleteFile() {
request({
method: 'delete',
url: 'https://bswadls.azuredatalakestore.net/webhdfs/v1/iModelAnalytics/readFile.txt?op=DELETE',
headers: {
"Authorization": "Bearer " + accessToken,
},
json: true
}, function (error, response, body) {
//Print the Response
console.log("***************Delete File*****************\n ");
console.log(body);
console.log('Response= \n');
console.log(response);
});
}

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

Trying to post api request

I having problem with making a API call to an external site.
I need to send a POST request to http://api.turfgame.com/v4/users with headers Content-type: application/js. But when I run this code it only loads and nothing more.
var request = require('request');
var options = {
uri: 'http://api.turfgame.com/v4/users',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
"name": "username"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
res.send(response.body);
}
});
The body need to be posted in json formate [{'name': 'username'}].
Can someone tell me what I have done wrong?
There are a few things wrong:
the address property in the "options" object should be "url" not
"uri"
you can use the "json" property instead of body
"res" is undefined in your response handler function
if you want the body to be an array, it needs to be surrounded in square brackets
here's a working sample that just logs the response:
var request = require('request');
var options = {
url: 'http://api.turfgame.com/v4/users',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
json: [{
"name": "username"
}]
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(response.body);
}
});

Resources