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);
}
});
Related
I was trying Gmail APIs. Using POSTMAN I have created oAuth 2.0 token and was able to hit the URL https://www.googleapis.com/gmail/v1/users/xyz#gmail.com/profile. But when I was trying same with my node project where I invoked the same using :
app.get('/getMail',getMail); in my index.js where getMail is as follows
exports.getMail = (req, res) => {
request({
url: "https://www.googleapis.com/gmail/v1/users/xyz#gmail.com/profile",
method: "GET",
headers: {
Authorization: 'Bearer token'
},
json: true
}, function(response) {
console.log(JSON.stringify(response, null, 4));
return res.json(response);
});
But I am getting the response as null. Any help would be appreciated.
Please change the callback function to include error. The callbacks are usually error-first callbacks meaning first argument is always error.
exports.getMail = (req, res) => {
request({
url: "https://www.googleapis.com/gmail/v1/users/xyz#gmail.com/profile",
method: "GET",
headers: {
Authorization: 'Bearer token'
},
json: true
// Here -> error
}, function(error, response) {
if (error) throw new Error(error); // Handle the error here.
console.log(JSON.stringify(response, null, 4));
return res.json(response);
});
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
})
}
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.
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);
});
}
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);
}
});
});