HttpRequest Node.js "Cannot set property 'UNSENT' of undefined" - javascript

I have a problem, when I try to run a simple http request I always get an error message.
Cannot set property 'UNSENT' of undefined
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
XMLHttpRequest('https://example.firebaseio.com/.json',
function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
}
}
);
How do I fix this problem?

I suggest you use the standard built-in NodeJS methods:
This code:
var http = require('http');
http.get('http://nodejs.org/dist/index.json', (res) => {
const statusCode = res.statusCode;
const contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error(`Request Failed.\n` +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error(`Invalid content-type.\n` +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.log(error.message);
// consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => rawData += chunk);
res.on('end', () => {
try {
let parsedData = JSON.parse(rawData);
console.log(parsedData);
} catch (e) {
console.log(e.message);
}
});
}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});
is taken from here

This will work.
var req = new XMLHttpRequest()
req.open('GET',url)
req.onload = function(){
if(req.status==200){
console.log(req.responseText)
}
else{
console.log(req.statusText)
}
}
req.onerror = function()
{
console.log('Network Error')
}
req.send()
})

Related

Request Params Node JS 500 Error

As the uri is generated is as expected and list data is shown in page but while sending the req in request method, 500 error occurs instead of retruning body.
uri: http://yufluyuinnepal.com/?vTRIPTYPE=O&vOPSID=O&vSTRFROM=KTM&vSTRFROMTXT=&vSTRTO=PKR&vSTRTOTXT=&vFLIGHTDATE=27-Nov-2018&vRETURNDATE=27-Nov-2018&vADULT=1&vCHILD=0&vNATIONALITY=NP&vNATIONALITYTXT=Nepal&
const uri = `http://yufluyuinnepal.com/?${queryString(query)}`;
console.log(uri);
const req = {
uri: uri,
};
request(req, (error, response, body) => {
if (error) {
return reject(error);
}
if (response.statusCode !== 200) {
return reject(new Error(`Expected 200 but got ${response.statusCode}`));
}
return resolve(body);
});
Let me know how can i return body and what is wrong in my code.
In Request npm module, specify what kind of request is it (GET/POST etc)
// Example GET Request
var options = {
method: "GET",
url:
uri,
headers:
{
// headers as per documentation
}
};
request(options, (error, response, body) => {
if(error){}
if(response.statusCode !== 200){}
return resolve(body);
})
This is your current implementation with a callback function.
const req = {
uri: uri,
method: 'GET'/'POST'
};
request(req, (error, response, body) => {
if (error) {
console.log(error);
}
if (response.statusCode !== 200) {
//Do something
}
console.log(body);
//Do something
});
When using request-promise module you should write something like this
var rp = require('request-promise');
const req = {
uri: uri,
method: 'GET'/'POST'
}
rp(req)
.then((res) => {
//Do something
})
.catch((error) => {
//Do something with error
});
Please try this
let requestp=require('request-promise');
var options = {
    method: 'POST',
    url: 'uri',
    resolveWithFullResponse: true,
    headers: {
                'Accept': 'application/json',
                'Content-Type' : 'application/json'
            },
            body: TextedValue
        };
     
        await  requestp(options).then(async function(Content){
           await requestp(options).then(async function(response){
                if (await response.statusCode == 200)
                    {
                        console.log(Content); // in ur case it is body
                    }
                 else
                    {
                        console.log("Response code "+response.statusCode+" .Try Again Later")
                   }
                })
           })

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

Removing duplicate error handling code Node.js

I have duplicated error handling code in my Node.js code, how can I make it better to get rid of duplicated code. I specifically want to ask error handling about this callback way, not the Promise way.
var request = require('request');
var URL = 'http://localhost:3000';
var getRanking = function get_rank(error, response, body) {
if (error) {
handleError(error);
} else {
if (response.statusCode != 200) {
handleError(response);
} else {
console.log('Response 1 ' + body);
request(URL + '/iso/country/' + JSON.parse(body).Country, getISO);
}
}
}
var getISO = function get_iso(error, response, body) {
if (error) {
handleError(error);
} else {
if (response.statusCode != 200) {
handleError(response)
} else {
console.log("Response 2 "+body);
request(URL+'/olympic/2016/medal/'+JSON.parse(body).iso,getMedalCount);
}
}
}
var getMedalCount = function get_medal_count(error, response, body) {
if (error) {
handleError(error);
} else {
if (response.statusCode != 200) {
handleError(response);
} else {
console.log("Response 3 " + body);
}
}
}
function handleError(err) {
console.log('Error ' + JSON.stringify(err))
}
request(URL+'/olympic/2016/ranking/4', getRanking);
Create a funciton handleResponse and write the response handling duplicated code in that funciton.
Call that function with required parameters as given,
var request = require('request');
var URL = 'http://localhost:3000';
var getRanking = function get_rank(error, response, body) {
handleResponse(error, response, body, 'getISO');
}
var getISO = function get_iso(error, response, body) {
handleResponse(error, response, body, 'getMedalCount');
}
var getMedalCount = function get_medal_count(error, response, body) {
handleResponse(error, response, body null);
}
function handleResponse(error, response, body, url) {
if (error) {
handleError(error);
} else {
if (response.statusCode != 200) {
handleError(response);
} else {
if(url == 'getISO')
{
request(URL + '/iso/country/' + JSON.parse(body).Country, getISO);
}
else if(url == 'getMedalCount')
{
request(URL+'/olympic/2016/medal/'+JSON.parse(body).iso,getMedalCount);
}
}
}
}
function handleError(err) {
console.log('Error ' + JSON.stringify(err))
}
request(URL+'/olympic/2016/ranking/4', getRanking);
You can try following code:
var request = require('request');
var URL = 'http://localhost:3000';
var getRanking = function get_rank(error, response, body) {
if (error) {
throw error;
}
if (response.statusCode != 200) {
throw new Error(response);
}
console.log('Response 1 ' + body);
request(URL + '/iso/country/' + JSON.parse(body).Country, getISO);
}
var getISO = function get_iso(error, response, body) {
if (error) {
throw error;
}
if (response.statusCode != 200) {
throw new Error(response);
}
console.log("Response 2 "+body);
request(URL+'/olympic/2016/medal/'+JSON.parse(body).iso,getMedalCount);
}
}
var getMedalCount = function get_medal_count(error, response, body) {
if (error) {
throw error;
}
if (response.statusCode != 200) {
throw new Error(response);
return;
}
console.log("Response 3 " + body);
}
try {
request(URL+'/olympic/2016/ranking/4', getRanking);
} catch(ex) {
console.log(ex);
}
Ok, as far as noone suggested such optimization, I will.
Instead of such block:
if (error) {
handleError(error);
} else {
if (response.statusCode != 200) {
handleError(response);
} else {
console.log("Response 3 " + body);
}
}
You can do this way:
if (error || response.statusCode != 200) handlerError(error || response);
else console.log("Response 3 " + body);
You can use following code to handle response.
var request = require('request');
var URL = "http://localhost:3000";
var getRanking = function get_rank (body) {
console.log("Response 1 " + body);
request(URL + '/iso/country/' + JSON.parse(body).Country, handleResponse.bind(null, getISO));
}
var getISO = function get_iso (body) {
console.log("Response 2 " + body);
request(URL + '/olympic/2016/medal/' + JSON.parse(body).iso, handleResponse.bind(null, getMedalCount));
}
var getMedalCount = function get_medal_count (body) {
console.log("Response 3 " + body);
}
function handleResponse (callback, error, response, body) {
console.log(error, response, body, callback)
if (error || response.statusCode != 200) {
console.log('Error ' + JSON.stringify(error))
}
else {
callback(body);
}
}
request(URL + '/olympic/2016/ranking/4', handleResponse.bind(null, getRanking));
The simpliest way to shorten your code would probably be the following :
function handleError(err, res) {
if(err){
console.log('Error '+JSON.stringify(err));
return false;
} else if(res.statusCode != 200) {
console.log('Error '+JSON.stringify(res));
return false;
} else {
return true;
}
}
// and then, use it in your functions like that :
var getRanking = function get_rank(error,response,body) {
if (handleError(err, res)) { // if there is no error, do your stuff
console.log("Response 1 "+body);
request(URL+'/iso/country/'+JSON.parse(body).Country,getISO);
}
}
But I think that's not very appropriate to JS, because JS can be used as a functional programming language (which is better) and this approach looks more procedural (like C language).
So, in my opinion, the below solution would be proper :
function handleError(successFunc) {
return function (error, response, body) {
if (error) {
throw new Error(error);
} else if(response.statusCode != 200) {
throw new Error(response);
} else {
successFunc(response);
}
}
}
// then, just pass your successFunc to your error handler :
var getRanking = function (response) {
// do your success stuff.
}
try {
request(URL+'/olympic/2016/ranking/4', handleError(getRanking));
} catch (e) {
// catch your error here
}
If your request is a success, getRanking will be executed, if this is a failure, the error will be logged and thrown.
With this solution, you can pass any function to your error handler and it will be used if the request succeed, if the request fails, the error handler will throw an error and then, you will be able to catch it.
Hope it helps,
Best regards

AJAX 404 with Node and Koa

Browser JS
'use strict';
window.onload = () => {
let form = document.getElementById('sign_up_form'),
username = form.elements[0],
password = form.elements[1],
confirm = form.elements[2],
email = form.elements[3],
errors = document.getElementById('sign_up_errors');
username.addEventListener('change', (e) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', '/validate_username');
xhr.send();
xhr.onreadystatechange = () => {
console.log(xhr.readyState);
if (xhr.readyState === 4) {
console.log(xhr.status);
if (xhr.status === 200) {
console.log('AJAX SUCCESS');
};
};
};
});
confirm.addEventListener('change', (e) => {
if (password.value != confirm.value) {
errors.children[1].innerHTML = 'Passwords do not match.';
} else {
errors.children[1].innerHTML = '';
};
});
form.addEventListener('submit', (e) => {
e.preventDefault();
let form_data = {
username: username.value,
password: password.value,
confirm: confirm.value,
email: email.value,
};
let xhr = new XMLHttpRequest();
xhr.open('POST', '/validate_signup');
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(form_data));
});
}
Server
'use strict';
let app = require('koa')(),
serve = require('koa-static'),
router = require('koa-router')(),
parse = require('koa-bodyparser'),
mongo = require('koa-mongo'),
fs = require('co-fs');
app.use(serve(__dirname + '/public'));
app.use(mongo({
uri: ******,
max: 100,
min: 1,
timeout: 30000,
log: false
}));
app.use(parse());
app.use(router.routes());
router.post('/validate_username', function *(next) {
console.log('username:');
console.log(this.request.body);
});
router.post('/validate_signup', function *(next) {
console.log('signup:');
console.log(this.request.body);
this.mongo.collection('users').findOne({'username': this.request.body.username}, (err, doc) => {
console.log(doc);
});
});
app.listen(5000);
The AJAX 'POST' request gives the form_data to the server and I can check the database but consoles 404 error. The AJAX 'GET' request just throws a 404 error after achieving readyState 4. I think I am using the routes incorrectly or am missing something in my AJAX requests but I am new to Koa.js and pretty much green all around so any help will be appreciated.
JS:
'use strict';
window.onload = () => {
let form = document.getElementById('sign_up_form'),
username = form.elements[0],
password = form.elements[1],
confirm = form.elements[2],
email = form.elements[3],
errors = document.getElementById('sign_up_errors');
username.addEventListener('input', (e) => {
let data = {username: username.value};
let xhr = new XMLHttpRequest();
xhr.open('POST', '/sign_up/username');
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = () => {
console.log(xhr.readyState);
if (xhr.readyState === 4 && xhr.status === 200) {
if (JSON.parse(xhr.responseText).username) {
console.log('unavailable');
} else {
console.log('available');
};
};
};
});
};
SERVER:
'use strict';
let router = require('koa-router')({
prefix: '/sign_up'
});
router.post('/username', function *(next) {
console.log('Checking username...');
yield new Promise((resolve, reject) => {
this.mongo.collection('users').findOne({'username': this.request.body.username}, (err, doc) => {
if (doc) {resolve(doc)}
else {reject()};
});
}).then((doc) => {
if (doc) {
console.log('Promise: ' + doc);
this.body = {username: false};
};
}).catch(() => {
console.log('Promise rejected.');
this.body = {username: true};
});
});
module.exports = router;

NODE JS cancel request

I am using this code to download files in node js :
var currentVideoRequest = null;
window.spawnVideoPlayer = function (url, subs, movieModel,tag) {
if(currentVideoRequest) {
try
{
currentVideoRequest.abort();
}
catch(err)
{
alert(err.message);
}
}
var fs = require('fs');
var urlrequest = currentVideoRequest = require('request');
urlrequest.get({url: url, encoding: 'binary'}, function (err, response, body) {
fs.writeFile(FILEURL, body, 'binary', function(err) {
});
});
}
And in the currentVideoRequest.abort(); i get this error:
Object function request(uri, options, callback) {
if (typeof uri === 'undefined') throw new Error('undefined is not a valid uri or options object.')
if ((typeof options === 'function') && !callback) callback = options
if (options && typeof options === 'object') {
options.uri = uri
} else if (typeof uri === 'string') {
options = {uri:uri}
} else {
options = uri
}
options = copy(options)
if (callback) options.callback = callback
var r = new Request(options)
return r
} has no method 'abort'
To add to #Etai's answer, you need to require the request module before using it for one instance of the request. Something like this:
var request = require('request');
// ...
// then later in the code
var urlrequest = request.get(uri, function(err, response, body) {
// process data here
});
// later, you'd abort this as:
urlrequest.abort();
Note that I'm saving the instance with var urlrequest = request.get(params, callback); so that I can call abort on it later.
your currentVideoRequest is a constructor for a request object, not a request object, which is why this is failing.
The request constructor returns a request object when invoked, i.e.
require('request')('uri', function(err, resp, body){})
you can use abort() method to stop that request.
var reqObj = request({uri: 'https://jsonplaceholder.typicode.com/albums' }, function (error, response, body) {
console.log('API requested ') ;
if (!err){
console.log(body);
}
else
{
console.log(err);
}
});
reqObj.abort();
I think you can use this method to get what you need.
I used async in this way, which makes both the code cleaner and less callback .
(async function main() {
try {
let urlRequest = await customRequest("http://127.0.0.1:8000/api/product/search?title=foo");
urlRequest.abort();
} catch (e) {
console.log(e);
}
})();
function customRequest(url) {
return new Promise((resolve, reject) => {
request.get(url, (err, res) => {
if (err) reject(err)
if (res.statusCode !== 200)
reject("my Error ");
resolve(res);
})
})
}
Also, if you do not need to answer the urlRequest variable,you can remove the await from the function as shown below.
try {
let urlRequest = customRequest("http://127.0.0.1:8000/api/product/search?title="); // run in background !
urlRequest.abort();
} catch (e) {
console.log(e);
}
Finally, since our request returns an exception if you make a mistake, you can write abort() in the catch block if needed.
(async function main() {
try {
var urlRequest =await customRequest("http://127.0.0.1:8000/api/product/search?title=");
} catch (e) {
urlRequest.abort();
console.log(e);
}
})();
Also, because the customRequest() function returns a promise note, you use then() instead of async await.

Categories

Resources