TypeError: Cannot read property 'on' of undefined - angularjs-directive

This error is while doing ionic push notification program ,here "on "is used to receive notification but because of following error i cant proceed
C:\Users\orcilia49\Desktop\AWpush_v1.1>ionic push --google-api-key AIzaSyCftJZvkhujq8IK4ayTbW9Me-Q9qb78n-c
C:\Users\orcilia49\AppData\Roaming\npm\node_modules\ionic\lib\ionic\push.js:140
response.on("data", function(data) {
^
TypeError: Cannot read property 'on' of undefined
at ClientRequest.<anonymous> (C:\Users\orcilia49\AppData\Roaming\npm\node_modules\ionic\lib\ionic\push.js:140:15)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at TLSSocket.socketErrorListener (_http_client.js:306:9)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at connectErrorNT (net.js:1015:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
C:\Users\orcilia49\Desktop\AWpush_v1.1>
event.js
angular.module('starter', ['ionic']).run(function($ionicPlatform) {
var push = new Ionic.Push({
"debug": true
});
push.register(function(token) {
console.log("My Device token:", token.token);
push.saveToken(token);
});
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})

Related

Unexpected token u in JSON at position 0 when sending info to other js file

I'm trying to make a chat bot, but I'm getting a error when I try to send data to another js file.
undefined:1
undefined
^
SyntaxError: Unexpected token u in JSON at position 0
at Object.parse (native)
at Request.request.get [as _callback] (D:\Projects\NodeJS\WoWBot-Discord\lib\user.js:12:27)
at self.callback (D:\Projects\NodeJS\WoWBot-Discord\node_modules\request\request.js:186:22)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at Request.onRequestError (D:\Projects\NodeJS\WoWBot-Discord\node_modules\request\request.js:878:8) at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at TLSSocket.socketErrorListener (_http_client.js:309:9)
at emitOne (events.js:96:13)
This is the bot.js file that I have. Here is where all the commands will be placed.
const Discord = require('discord.js');
const client = new Discord.Client();
const realms = require('./lib/realms');
const user = require('./lib/user');
const guild = require('./lib/guild');
const race = require('./lib/race');
client.on('ready', () => {
console.log('bot is online');
client.user.setStatus('online');
client.user.setGame('In progress');
});
client.on('message', message =>{
var msg = message.content.split(' ');
switch (msg[0]) {
case ("player"):
let country = msg[1];
let realm = msg[2];
let pname = msg[3];
user.characterProfile(country, realm, pname);
break;
}
});
client.login('');
But I am trying to get the data from a other js file, because I don't want it to be a cluster of code mixed together.
This is the file user.js. In here I will get the specific data from a api url.
const request = require('request');
function characterProfile(country, realm, uname) {
request.get(`https://${country}.api.battle.netwow/character/${realm}/${uname}?locale=en_US&apikey=4p7ha7t5udqa7fgmpasm9xhb6a9vmm9u`, (err, res, body) => {
const test = JSON.parse(body);
console.log(test.name);
});
}
exports.characterProfile = characterProfile;
1 thing that I noticed is when I change the request.get url to a normal link without for example ${country} added into it, the result will pe printed fine without any errors.
Any ideas how I can fix it?

nodejs http JSON API not working

I want to use an anime database API and get the information of anime shows, heres what i tried to do
var http = require("http");
const url = "http://kitsu.io/api/edge/anime?=cowboy%20bebop";
http.get(url, res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
body = JSON.parse(body);
//then do stuff here
});
});
and the error i get is
undefined:1
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at IncomingMessage.res.on
(C:\Users\Admin\Desktop\project\index.js:113:17)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
line 113 is
body = JSON.parse(body);
(from the first snippet of code)
the documentation to the API is here.
JSON.parse(body);
SyntaxError: Unexpected end of JSON input
is thrown when body is having invalid json. Check the string value and make sure it is in json format and without any errors.
JSON.parse which can give you "unexpected end of input" errors if the supplied byte length does not match the data.
You're giving the API an invalid JSON:API query in the request (which causes it to return a HTML error page unfortunately)
You want to use the filter query like so: http://kitsu.io/api/edge/anime?filter[text]=cowboy%20bebop

response from HTTP Request cannot convert from string to JSON

This is the function of the http.request, as follow:
var post_req =http.request(options,function(res){
console.log('STATUS:'+res.statusCode);
console.log('HEADERS: '+JSON.stringify(res.headers));
var str ='';
res.setEncoding('utf8');
res.on('data',function (chunk){
str += chunk;
});
res.on('end',function(){
console.log("message="+str);
});
res.on('error',function(e){
});
var token= JSON.parse(str);
console.log(token);
This is the error I got from the console, can anybody tell me what's wrong with my code?
undefined:0
^
SyntaxError: Unexpected end of input
at Object.parse (native)
at ClientRequest.<anonymous> (/Users/guojiaqi/Documents/workspace/ejs/APIintegration.js:27:18)
at ClientRequest.g (events.js:180:16)
at ClientRequest.emit (events.js:95:17)
at HTTPParser.parserOnIncomingClient [as onIncoming] (http.js:1692:21)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
at CleartextStream.socketOnData [as ondata] (http.js:1587:20)
at CleartextStream.read [as _read] (tls.js:513:12)
at CleartextStream.Readable.read (_stream_readable.js:340:10)
at EncryptedStream.write [as _write] (tls.js:368:25)
Your str variable is empty because you're using event handlers to read data from the network stream but you're not waiting for those to finish when you start doing stuff with str. Move JSON.parse(str) inside of res.on('end', ...) so that you can parse the JSON after you've finished downloading.

Is there an end event when using the request module?

I am using the request module that found on npm, and I am wondering if there is an end event that i can bind to. The reason i'm asking is because i am requesting a JSON and i am getting an error if i try to use JSON.parse directly after i get the response. The code looks something like this.
var parseJSON = function(JSON, cb){
var parsed = JSON.parse(JSON);
cb(parsed);
};
request(url, function(error, response, body) {
parseJSON(body, function(bodyObj){
// do stuff with bodyObj...
});
});
Trying to do this, gives the following error...
var parsed = JSON.parse(JSON);
^
has no method 'parse'
at parseJSON (/home/stephen/Desktop/redditjs/reddit.js:31:20)
at Requester.collector [as _callback] (/home/stephen/Desktop/redditjs/reddit.js:43:5)
at Request.init.self.callback (/home/stephen/node_modules/request/main.js:122:22)
at Request.EventEmitter.emit (events.js:99:17)
at Request.<anonymous> (/home/stephen/node_modules/request/main.js:661:16)
at Request.EventEmitter.emit (events.js:126:20)
at IncomingMessage.Request.start.self.req.self.httpModule.request.buffer (/home/stephen/node_modules/request/main.js:623:14)
at IncomingMessage.EventEmitter.emit (events.js:126:20)
at IncomingMessage._emitEnd (http.js:366:10)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23
The issue is that you're overriding the global JSON object.
This will work just fine:
var parseJSON = function(MyJSON, cb){
var parsed = JSON.parse(MyJSON);
cb(parsed);
};

Error when using JSON.parse in node.js

I'm writing a simple program that makes a request to reddit, and gets back the page in JSON format. I do this by appending '.json' to the end of the reddit url. For example, if i wanted to get the page for my profile i would do "www.reddit.com/user/stebon24.json".
Here is my program so far. I will log and describe the error below.
var http = require('http');
var options = {
host: 'www.reddit.com',
path: ''
};
module.exports = function(username) {
console.log(username);
options.path = '/user/' + username + '.json';
var userData;
http.get(options, function(res) {
res.on('data', function(data) {
userData += data;
console.log(userData);
});
res.on('end', function() {
userData = JSON.parse(userData);
console.log(userData);
});
});
};
As for the error, it happens when the program gets to the point where it needs to run JSON.parse(). I know this because i can see it output the raw JSON from when i log the result on the 'data' event. Then this error is output...
undefined:1
undefined{"kind": "Listing", "data": {"modhash": "", "children": [{"kind": "t1
^
SyntaxError: Unexpected token u
at Object.parse (native)
at IncomingMessage.module.exports (/home/stephen/Desktop/karmacrawler/engine/crawlUser.js:23:20)
at IncomingMessage.EventEmitter.emit (events.js:126:20)
at IncomingMessage._emitEnd (http.js:366:10)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
at Socket.socketOnData [as ondata] (http.js:1367:20)
at TCP.onread (net.js:403:27)
Remember to set an initial value for userData so that it won't initialize as "undefined":
var userData = '';