NodeJS res.on() is not triggered. res.on() not a function - javascript

I have a NodeJS code using request module to make a request to the server. The code works fine if I use 'http.request' but shows error on res.on() while using request to make the call. Following is the part showing the error:
const Request = require("request");
.
.
.
function getRequiredTime(lc, lat, lon, id, response, callback) {
const start = new Date();
const ReqObj = {
host: 'localhost',
port: process.env.PORT,
path: '/something/' + lc + '/' + lat + '/' + lon +'/' + id,
method: 'GET'
};
const RespObj = {};
const requestBody = {};
requestBody.id = id;
requestBody.app_name = "someApp";
requestBody.hostname = ReqObj.hostname;
requestBody.path = ReqObj.path;
requestBody.msg = "Some message";
requestBody.body = "";
logger.info(JSON.stringify(requestBody));
const getReq = Request(ReqObj, function (res) {
if (res.statusCode === 400) {
response.send("Some message");
} else if (res.statusCode === 500) {
response.send("Some message");
} else if (res.statusCode === 501) {
response.send("Some message");
} else {
let duration = parseInt(15);
res.on('data', function (durationtime) {
const end = new Date();
const end = *****;
const responseDat = {
'id': id,
'start': start,
'end': end,
'time': end,
'service_name': 'someName'
};
duration += parseInt(durationtime);
const time = parseInt(duration);
RespObj.id = id;
RespObj.app_name = "getApp";
RespObj.msg = "Some message";
RespObj.body = time;
logger.info(JSON.stringify(RespObj));
callback(time);
});
res.on('error', function (error) {
logger.error(`ERROR`);
});
}
});
getReq.end();
};
.
.
.
This is the error I am getting when trying to hit the url with ARC or postman:
TypeError: res.on is not a function at Request._callback
at self.callback
at Request.emit
at Request.init
at new Request

res.on() is an event of http module, not request module. In your case, body contains your data and no need res.on event when change your callback function to
const getReq = Request(ReqObj, function (err, res, body) {

Related

javascript promise callback

I am calling a javascript function , which in turn calls a web service;The response of this service is used to call another function which also calls a service. At end of both services we set session attributes. This code gives no errors, but the callback gets called before the service has returned data. The main motive of this code is to set the session attributes before return of flow from this code, when the callback gets called before the service has returned values the session attributes are not set and the requirement of the code is not fulfilled.
'use strict';
function close(sessionAttributes, fulfillmentState, message) {
return {
sessionAttributes,
dialogAction: {
type: 'Close',
fulfillmentState,
message : 'For security purpose answer these questions '
},
};
}
function getSecurityQuestions(intentRequest, context, post_options, callback){
const sessionAttributes = intentRequest.sessionAttributes || {};
var policynumber = sessionAttributes.policynumber;
var interactionID = sessionAttributes.interactionID;
var body = "";
var body2;
const http = require('https');
const promise = new Promise((resolve, reject) => {
const post_data = JSON.stringify({"Purpose":"SecurityQuestions", "InteractionID":interactionID, "SearchStringAcctNum":policynumber});
//ignores SSL
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var post_request = http.request(post_options, function(res) {
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
context.done(body);
resolve(body);
});
res.on('error', function(e) {
reject(Error(e.message));
context.fail('error:' + e.message);
});
});
// post the data
post_request.write(post_data);
post_request.end();
});
callback( promise.then((body) => {
body2 = JSON.parse(body);
sessionAttributes.question1 = body2.SecurityDetails[0].Question;
close(sessionAttributes, 'Fulfilled');
}, (error) => {
console.log(error.message);
})
);
}
function getInteraction(intentRequest, context, callback) {
const slots = intentRequest.currentIntent.slots;
var policynumber = "PA"+slots.PolicyNumber;
var questionOne = slots.questionOne;
var questionTwo = slots.questionTwo;
const sessionAttributes = intentRequest.sessionAttributes || {};
console.log("policy number : "+policynumber + "question 1 : "+questionOne + "question 2 : "+questionTwo);
sessionAttributes.policynumber = policynumber;
var body = "";
var body2;
// An object of options to indicate where to post to
var post_options = {
host: 'example.com',
protocol: 'https:',
port: '3000',
path: '/hiddenPath',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
const http = require('https');
const promise = new Promise((resolve, reject) => {
const post_data = JSON.stringify({"Purpose":"CreateInteraction"});
//ignores SSL
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var post_request = http.request(post_options, function(res) {
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
context.done(body);
resolve(body);
});
res.on('error', function(e) {
console.log("rejected here");
reject(Error(e.message));
context.fail('error:' + e.message);
});
});
// post the data
post_request.write(post_data);
post_request.end();
});
callback( promise.then((body) => {
body2 = JSON.parse(body);
console.log("interaction ID : "+body2.InteractionID);
sessionAttributes.interactionID = body2.InteractionID;
getSecurityQuestions(intentRequest, context, post_options, callback);
}, (error) => {
console.log('Promise rejected.');
console.log(error.message);
}));
}
// --------------- Intents -----------------------
/**
* Called when the user specifies an intent for this skill.
*/
function dispatch(intentRequest, context, callback) {
const intentName = intentRequest.currentIntent.name;
if (intentName === 'currIntent') {
return getInteraction(intentRequest, context, callback);
}
throw new Error(`Intent with name ${intentName} not supported`);
}
// --------------- Main handler -----------------------
function loggingCallback(response, originalCallback) {
console.log("logging callback called......");
originalCallback(null, response);
}
exports.handler = (event, context, callback) => {
try {
dispatch(event, context, (response) => loggingCallback(response, callback));
} catch (err) {
callback(err);
}
};
You should resolve your promise only after the request ends.. Have updated your sample below. Hope it helps. Also, you were sending an invalid object as your post body. Fixed that as well.
function getValue(context, post_options, callback) {
var body = "";
var body2;
const http = require('http');
const promise = new Promise((resolve, reject) => {
// INVALID OBJECT
//const post_data = JSON.stringify({"something"});
const post_data = JSON.stringify({
something: "something"
});
//ignores SSL
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var post_request = http.request(post_options, function(res) {
res.on('data', function(chunk) {
body += chunk;
console.log("inside " + JSON.stringify(body));
// DONT RESOLVE HERE, REQUEST IS NOT COMPLETE
//resolve(body);
});
res.on('end', function() {
context.done(body);
//RESOLVE HERE INSTEAD
resolve(body);
});
res.on('error', function(e) {
reject(Error(e.message));
context.fail('error:' + e.message);
});
});
// post the data
post_request.write(post_data);
post_request.end();
});
promise.then((body) => {
console.log("response data " + JSON.stringify(body));
body2 = JSON.parse(body);
callback(delegate(sessionAttributes, intentRequest.currentIntent.slots));
}, (error) => {
console.log('Promise rejected.');
console.log(error.message);
});
}

Returning response from https node request

I'm trying to retrieve the response(var body) from response_handler function to my /image/search route. But the problem is I cannot do it by making it (var body) a global variable since it's asynchronous.
router.get('/imagesearch/:term', (req, res) => {
let term = req.params.term;
bing_web_search(term);
res.json('trying to add json response here')
});
let host = 'api.cognitive.microsoft.com';
let path = '/bing/v7.0/search';
let response_handler = function (response) {
let body = '';
response.on('data', function (d) {
body += d;
});
response.on('end', function () {
console.log('\nRelevant Headers:\n');
for (var header in response.headers)
// header keys are lower-cased by Node.js
if (header.startsWith("bingapis-") || header.startsWith("x-msedge-"))
console.log(header + ": " + response.headers[header]);
body = JSON.stringify(JSON.parse(body), null, ' ');
console.log('\nJSON Response:\n');
console.log(body);
});
response.on('error', function (e) {
console.log('Error: ' + e.message);
});
};
let bing_web_search = function (search) {
console.log('Searching the Web for: ' + search);
let request_params = {
method : 'GET',
hostname : host,
path : path + '?q=' + encodeURIComponent(search),
headers : {
'Ocp-Apim-Subscription-Key' : subscriptionKey,
}
};
let req = https.request(request_params, response_handler);
req.end();
}

Trouble Getting JSON Data

I am pretty new to back end programming with JavaScript and have written some code to query a database and return the results as JSON. It seems to be working correctly in the browser, but my iOS code isn't getting any data from it. I have it running locally for now while testing. If you look in my Swift that gets the data from the URL, I'm getting the NO JSON from the print statement in the catch.
JavaScript
'use strict';
var util = require('util');
var sql = require("mssql");
var express = require('express');
var port = process.env.PORT || 1337;
var membershipNumber;
var queryString;
var app = express();
app.get('/membership/:number', function (req, res) {
console.log("\nPARAMS:");
console.log(req.params.number);
membershipNumber = req.params.number;
queryString = util.format('SELECT major_key, company, status, paid_thru FROM name WHERE major_key = \'%s\' and member_record = 1', membershipNumber);
console.log("\nQUERY:");
console.log(queryString);
res.setHeader('Content-Type', 'application/json');
res.set('Content-Type', 'application/json');
membershipStatusQuery(queryString, res);
});
app.get('/', function (req, res) {
var dictionary = [];
dictionary.push({
key: "none"
});
var jsonDict = JSON.stringify(dictionary);
res.setHeader('Content-Type', 'application/json');
res.set('Content-Type', 'application/json');
res.send(jsonDict);
});
function membershipStatusQuery(query, response) {
var config = {
server: 'DB_Server',
database: 'testDB',
user: 'sa',
password: 'password',
port: 1433
};
var connection = new sql.Connection(config);
connection.connect().then(function () {
var req = new sql.Request(connection);
req.query(query).then(function (recordset) {
connection.close();
response.send(results);
})
.catch(function (err) {
console.log(err);
connection.close();
response.send(err);
});
})
.catch(function (err) {
console.log(err);
response.send(err);
});
}
app.listen(port, function () {
console.log("Listening on port %s", port);
});
RESULTS
[{"major_key":"0001354648","company":"Membership of David Metzgar","status":"A","paid_thru":"2017-10-31T00:00:00.000Z"}]
iOS Swift Code
Class to get JSON from URL:
import UIKit
class GetJSON: NSObject {
func getJSONFrom(urlString: String) -> JSON {
let url = URL(string: urlString)
var data = Data()
do {
data = try Data(contentsOf: url!)
} catch {
print("No JSON")
// TODO: Display error
}
let json = JSON(data: data)
return json
}
}
Method from another class to use JSON:
func getQueryResultsJSON() {
print("http://localhost:1337/membership/\(memberNumberTextField.text!)")
// let jsonURL = "http://localhost:1337/membership/\(memberNumberTextField.text!)"
let jsonURL = "http://localhost:1337/membership/0001354648"
let getJSON = GetJSON()
self.resultsArray = getJSON.getJSONFrom(urlString: jsonURL)
if let dictionary = resultsArray?[0].dictionaryObject {
if let status = dictionary["status"] {
if status as! String == "A" {
print(dictionary)
print("Provided membership is active")
// membership is active
// TODO: save info and display membership card
} else {
print(dictionary)
print("Provided membership is NOT active")
// membership is not active
// TODO: display alert
}
} else {
print("DOESN'T EXIST!")
// membership number does not exist
// TODO: display alert
}
} else {
print("NOTHING!")
}
}
let url = NSURL(string: "your url")!
let request = NSMutableURLRequest(url: url as URL)
// request.httpMethod = "POST"
// request.httpBody = jsonData
//request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
if error != nil {
return
}
do {
let userObject = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: String]
if userObject != nil {
// do something
}
} catch let jsonError {
print(jsonError)
print(String(data: data!, encoding: String.Encoding.utf8)!)
}
}
task.resume()

Node.js: Cannot read property [...] of undefined

I am currently working on a node.js code for Amazon Alexa.
I try to write to a REST server and want to output the changes by alexa's speech, I am also using alexa-sdk. I get this error:
TypeError: Cannot read property 'request' of undefined
at writeIntent (/var/task/index.js:41:14)
at /var/task/index.js:125:25
at IncomingMessage.<anonymous> (/var/task/getRestData.js:6:13)
at emitOne (events.js:77:13)
at IncomingMessage.emit (events.js:169:7)
at IncomingMessage.Readable.read (_stream_readable.js:360:10)
at flow (_stream_readable.js:743:26)
at resume_ (_stream_readable.js:723:3)
at nextTickCallbackWith2Args (node.js:437:9)
at process._tickDomainCallback (node.js:392:17)
This is the writeIntent function:
//main helper function for write-intents
function writeIntent(slot, report, slotURL, event, context) {
var http = require('http');
var options = {
host: '1.2.345.678',
path: '/path/' + slotURL,
port: '8020',
method: 'POST',
'Content-Type': 'application/json'
};
callback = function (response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
if (report.toString() !== '') {
output(report, context);
}
});
};
//write alexa slot to server
if (event.request.type === "IntentRequest") {
var req = http.request(options, callback);
var postData = '{"$type":"string","?value":"' + slot + '"}';
req.write(postData);
req.end();
}
}
And this is the code in the intent handler inside index.js:
var rest = require('./getRestData');
slot = 'Weather';
rest.getRestData('varWeatherState', function (state) {
rest.getRestData('varWeatherTemperature', function (temp) {
report += slot + ', the weather is ' + state
+ ', the temperature is ' + temp;
writeIntent(slot, report, 'varTheme', this.event, this.context);
writeIntent((new Date).getTime(), '',
'varThemeTrigger', this.event, this.context);
});
});
And this is the getRestData function:
var getRestData = function (node, callback) {
var http = require('http');
var url = 'http://website.com/' + node + '?value';
http.get(url, function (response) {
response.on('data', function (data) {
callback(data);
});
});
}
exports.getRestData = getRestData;
event is defined as parameter in index.js:
exports.handler = function (event, context) {
//init alexa-sdk
var Alexa = require('alexa-sdk');
var alexa = Alexa.handler(event, context);
alexa.appId = 'amzn1.ask.skill.2732c691-3bcc-4741-80f9-ddf57405be70';
alexa.registerHandlers(handlers);
alexa.execute();
};
Outside of the getRestData function, I can access event with this.event.
How can I feed event (and context) through getRestData to writeIntent?

Post - Cannot GET error - Local server

I am trying to create an API using a local server for testing. The route
'GET' works fine, however 'POST' has a problem and it is returning 'Cannot GET /add/name'. I am developing the API using node.js and Express. Why am I receiving get when the route is set to 'POST'? Where is the problem?
var fs = require('fs');
var data = fs.readFileSync('events.json');
var allEvents = JSON.parse(data);
console.log(allEvents);
console.log('Server running.');
var express = require('express');
var app = express();
var sever = app.listen(3000, listening);
function listening() {
console.log('Serving...');
}
app.use(express.static('website'));
//GET and send all data from JSON
app.get('/all', sendAll);
function sendAll(request, response) {
response.send(allEvents);
}
//POST new data to JSON
app.post('/add/:name', addData);
function addData(request, response) {
var newData = request.params;
var name = newData.name;
var eventType = newData.eventType;
var reply;
// var newEvent = {
// name: ":name",
// eventType: ":eventType",
// };
var newData = JSON.stringify(allEvents, null, 2);
fs.writeFile('events.json', newData, finished);
function finished(err) {
console.log('Writting');
console.log(err);
var reply = {
word: word,
score: score,
status: 'Success'
}
response.send(reply);
}
}
Request
$(function() {
//HTML
var $list = $('#list');
var jsonURL = '../events.json'
$.ajax({
type: 'GET',
url: '/all',
success: function(data) {
console.log('Data received', data);
$.each(data, function (type, string) {
$list.append('<li>' + type + " : " + string + '</li>');
});
},
error: function (err) {
console.log('Error, data not sent.', err);
}
});
$('#submit').on('click', function () {
// var newEvent = {
// name: $name.val(),
// eventType: $eventType.val(),
// };
var name = $('#fieldName').val();
var eventType = $('#fieldEventType').val();
console.log(name);
$.ajax({
type: 'PUT',
url: '/add/' + name,
success: function (addData) {
$list.append('<li>name: ' + name + '</li>');
},
error: function (err) {
console.log('Error saving order', err);
}
});
});
});
Thank you in advance.
For testing POST request, you can use Postman to test it. If you use the browser to call the api, it will be GET method instead of POST.

Categories

Resources