(I am new to JS, node.js and Heroku so I hope the question is clear)
I have an Heroku node.js app, I was able to set up Heroku scheduler to run a task every 1 hour.
The task runs on time and the method fireHook() is called (I can see the log in the console) but the request does not work (I don't get any lo or error).
This is the job:
#!/usr/bin/env node
var request = require('request')
function fireHook(){
console.log("firing")
request({
url: 'https://XXXXXX.herokuapp.com/jobs',
method: "POST",
headers: { "content-type": "application/json" },
json: {"user_id":{ "id":"ddddd"}}
}, function(error, response, body) {
console.log(response)
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
} else {
console.log('success: ', body)
reportToSnitch()
}
})
}
fireHook();
process.exit();
2 questions:
Why sold the request not working ?
I am currently using a webhook to call my main app, is there a better way to call a function on the main app from the script directly?
Thanks
I think your process.exit() is killing your script before the request has received its response. Try to move it into the callback:
#!/usr/bin/env node
var request = require('request')
function fireHook(){
console.log("firing")
request({
url: 'https://XXXXXX.herokuapp.com/jobs',
method: "POST",
headers: { "content-type": "application/json" },
json: {"user_id":{ "id":"ddddd"}}
}, function(error, response, body) {
console.log(response)
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
} else {
console.log('success: ', body)
reportToSnitch()
}
process.exit();
})
}
fireHook();
JavaScript is asynchronous so you have to be careful to consider where and when certain events will occur. If your reportToSnitch() function is async as well, you may need to fire the process.exit() at the end of that function.
Related
I am working on grunt-http.
If I pass an invalid credential then it's throwing an error like:
Running "http:test_grunt_http" (http) task
Fatal error: 401 {"status":"error","errorCodes":["INVALID_CREDENTIALS"],"data":{"message":"Invalid email or password. Please try again."}}
Gruntfile.js
module.exports = function (grunt) {
require('time-grunt')(grunt);
grunt.config.init({
http: {
"test_grunt_http": {
options: {
url: "http://localhost:8000/studentdb/login/auth/",
headers: {
"Accept": "*/*",
"Content-Type": "application/json"
},
method: 'POST',
body: JSON.stringify({
email: 'loginID',
password: 'loginPassword'
}),
callback: function (error, response, body) {
if (response.statusCode === 200) {
var resData = JSON.parse(body);
console.log('body: ', resData);
} else {
console.warn(error); // error is not handling
}
}
}
}
}
});
require('load-grunt-tasks')(grunt);
grunt.loadNpmTasks('grunt-http');
grunt.registerTask('default', ['http', 'func2']);
grunt.registerTask('func2', function (key, value) {
console.log("I am with in function-02");
});
};
run : grunt default
Output:
If I pass a valid credential then both grunt task (http, func2) is working properly. But if I pass a wrong credential then stop grunt file execution at first task execution time. That means 2nd is not executing in this scenario.
Now my question is, how to handle grunt-http callback error?
This issue is resolved.
If add ignoreErrors: true within option, then it's working properly.
options: {
ignoreErrors: true,
. . .
}
But I am not able to print the http-error. Is there any way to capture it?
I'm using NodeJs to try to upload an attachment to a Jira Issue via the Jira Rest API.
The api expects multipart/form-data so this is how I'm calling it in Node:
function uploadAttachments(supportFormData, callback) {
const url =
'https://somewhere.com/jira/rest/api/2/issue/' +
supportFormData.issueId +
'/attachments';
var options = {
url: url,
headers: {
Authorization: { user: username, password: password },
'X-Atlassian-Token': 'nocheck'
}
};
var r = request.post(options, function(err, res, body) {
if (err) {
console.error(err);
callback(false);
} else {
console.log('Upload successful! Server responded with:', body);
callback(false);
}
});
var form = r.form();
form.append('file', supportFormData.attachments[0].contents, {
filename: supportFormData.attachments[0].fileName,
contentType: supportFormData.attachments[0].contents
});
}
The error I'm receiving is:
org.apache.commons.fileupload.FileUploadException: Header section
has more than 10240 bytes (maybe it is not properly terminated)
The "supportFormData.attachments[0].contents" is ofType Buffer.
Any suggestions as to what could be causing this error?
I ran into this same issue and it turns out JIRA (or Java) requires \r\n as new line character. After I changed \n to \r\n my requests went through without problem.
If its a basic auth change options object to
let auth = new Buffer(`${username}:${password}`).toString('base64');
var options = {
url: url,
headers: {
Authorization: `Basic ${auth}`,
'X-Atlassian-Token': 'nocheck'
}
};
I am new to the working with TAPE JS for testing. I have it all setup and working, and it works fine with regular tests. But I am trying to test a unique REST API based product that relies on certain calls to have been made before the next call has the information needed to have a successful call.
So here are the first two calls I am trying to get working:
var SessionId;
test('beginIqsSession', function (assert) {
assert.plan(1);
var requestData = {"ProductDataArray":{"Feid":"GIQNY","AltData":"SaneID:null","Debug":"false","PageId":"1.1"}};
request({
url: 'http://192.168.99.100/Iqs/api.php/beginIqsSession',
method: "POST",
json: requestData
}, function(error, response, json){
if(json.responseDataPayload.SessionId)
{
SessionId = json.responseDataPayload.SessionId;
assert.equal(1,1);
}
});
assert.end();
});
test('validateAddress', function (assert) {
assert.plan(2);
console.log("Retrieving validateAddress response");
var requestData = {"SessionId":SessionId,"ValidateAddressDataArray":{"PropertyStreetNumber":"20671","PropertyStreetName":"mountain vista dr","PropertyCity":"anchorage","PropertyState":"AK","PropertyZipCode":"99577"}};
console.log(SessionId);
request({
url: 'http://192.168.99.100/Iqs/api.php/validateAddress',
method: "POST",
json: requestData
}, function (error, response, body) {
if (!error) {
console.log(body);
}
else {
console.log("error: " + error)
}
});
assert.end();
});
So basically in the code above, I am trying to test beginIqsSession, wait for its response, and store a piece of data from that response that future calls require to be sent in.
in validateAddress you'll see I am trying to pass SessionId in which was returned in the previous call, but because this test is being run at the same time as the previous test, this variable is still empty. How can I make the second call, and all future calls, to wait for the previous call to run?
assert.plan apparently doesn't work in this way.
You could use the Promise API
var SessionId;
let p1 = new Promise((resolve, reject) => {
test('beginIqsSession', function (assert) {
assert.plan(1);
var requestData = {"ProductDataArray":{"Feid":"GIQNY","AltData":"SaneID:null","Debug":"false","PageId":"1.1"}};
request({
url: 'http://192.168.99.100/Iqs/api.php/beginIqsSession',
method: "POST",
json: requestData
}, function(error, response, json){
if(json.responseDataPayload.SessionId)
{
SessionId = json.responseDataPayload.SessionId;
assert.equal(1,1);
resolve(SessionId);
}
});
assert.end();
});
})
p1.then((SessionId) => {
test('validateAddress', function (assert) {
assert.plan(2);
console.log("Retrieving validateAddress response");
var requestData = {"SessionId":SessionId,"ValidateAddressDataArray":{"PropertyStreetNumber":"20671","PropertyStreetName":"mountain vista dr","PropertyCity":"anchorage","PropertyState":"AK","PropertyZipCode":"99577"}};
console.log(SessionId);
request({
url: 'http://192.168.99.100/Iqs/api.php/validateAddress',
method: "POST",
json: requestData
}, function (error, response, body) {
if (!error) {
console.log(body);
}
else {
console.log("error: " + error)
}
});
assert.end();
});
});
I am not very familiar with Node js and as well as dealing with http requests so pardon me if this is something obvious.
I am following the examples on this website:
$.ajax({
url: 'https://api.wit.ai/message',
data: {
'q': 'set an alarm in 10min',
'access_token' : 'MY_WIT_TOKEN'
},
dataType: 'jsonp',
method: 'GET',
success: function(response) {
console.log("success!", response);
}
});
I am trying to create the equivalent of this but in Node Js. I attempted to use 'node request' however my code is not working. I have attempted a lot of variations of this but to no avail.
Here is an example:
var request = require('request');
var url = 'https://api.wit.ai/message';
var data = {
'q': 'hello test123 trying to get entities from this message',
'access_token': 'MY_WIT_TOKEN'
};
request.get({ url: url, formData: data }, function (err, httpResponse, body) {
if (err) {
return console.error('post failed:', err);
}
console.log('Get successful! Server responded with:', body);
});
When I compile this code, my terminal replies with:
Something went wrong. We've been notified.
Use http:
var http = require('http');
http.get({
host: 'api.wit.ai',
path: '/message'
}, function(response) {
var body = '';
// get all data from the stream
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
// all data received
console.log(body)
});
});
To anyone interested here is the answer using node request that worked for me.
var request = require('request');
var headers = {
'Authorization': 'Bearer <WIT_TOKEN>'
};
var options = {
url: 'https://api.wit.ai/message?v=20160607&q=hello',
headers: headers
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);
I have a node server that pulls info from a php server and sends it over where it needs to be through a callback. Once or twice ad day the server gets stuck in an infinite loop and I think it's because I'm not properly handling the connection between the the php and node server. I posted my authentication code below. Anyone have any ideas?
exports.authenticate = function(request, callback) {
var https = require('https');
var options = {
hostname: 'www.mysite.com',
port: 443,
path: '/site/chatauth?id=' + request.sessionID,
method: 'GET',
};
var req = https.request(options, function(res) {
//console.log("statusCode: ", res.statusCode);
// console.log("headers: ", res.headers);
res.on('data', function(d) {
// process.stdout.write(d);
});
});
req.end();
req.on('response', function (response) {
var data = '';
response.setEncoding('utf8');
response.on('data', function(chunk) {
data += chunk;
});
// console.log (request.sessionID);
response.on('end', function() {
try {
callback(JSON.parse(data));
} catch(e) {
callback();
console.log("authentication failed");
}
});
});
};
are you sure authenticate function? Your code is seems to be perfect. There is two thing you have to do
1.Make callback on request error, request timeout and request abort.
2.Get deep insight about your callback, In following code you call same function on throwing exception. Are you sure about this?. This could make possibly loop, if it is again reach "authentication" function.
try {
callback(JSON.parse(data));
} catch(e) {
callback();
console.log("authentication failed");
}
I can't find any errors in your code, but due to emitter/asynchronous way perhaps I didn't catch it completely.
I personally use npm module request (Simplified HTTP request client) w/o any problems so far.
You could easily give it a try:
var request = require('request');
request({
uri: 'https://www.mysite.com/site/chatauth?id=' + request.sessionID,
encoding: 'utf8',
timeout: 20000,
strictSSL: true
}, function (err, response, body) {
if (err || response.statusCode !== 200) {
// some error handling
callback('error');
return;
}
callback(null, JSON.parse(body));
});