Saturday 22 April 2017

custom Attribute Based Access Control | Angular & Rails

I am implementing Attribute Based Access Control in angular typescript application with rails server.

I've searched for different solutions like followings but could not manage to implement cause of unclear solutions.

  1. Custom Roles Based Access Control RBAC in ASP NET
  2. simple attribute based access control with spring

please help guide me how can I implement custom access control system in efficient way without using GEM or Package.

any suggestion and tips are welcome.



via LukyBoy -KU

require('./js/libs/stats.min.js'); and require('./js/libs/dat.gui.min.js') phrase in three.js javascript file doesn't work

require('./js/libs/stats.min.js'); and require('./js/libs/dat.gui.min.js') phrase in three.js javascript file in my code doesn't work.this is the phrase:

     var THREE=require('../build/three.js')
        window.THREE = THREE;

         require('./js/controls/DragControls.js')
         require('./js/controls/OrbitControls.js')
         require('./js/controls/TransformControls.js')


        require('./js/libs/stats.min.js');

        require('./js/libs/dat.gui.min.js')
/*
        var Stats=require('./js/libs/stats.min.js')
window.Stats = Stats;
        var dat=require('./js/libs/dat.gui.min.js')
window.dat = dat;
*/

and this is a part of code:

function init() {


            container = document.getElementById( 'container' );

            scene = new THREE.Scene();
            camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
            camera.position.set( 0, 250, 1000 );
            scene.add( camera );

            scene.add( new THREE.AmbientLight( 0xf0f0f0 ) );
            var light = new THREE.SpotLight( 0xffffff, 1.5 );
            light.position.set( 0, 1500, 200 );
            light.castShadow = true;
            light.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 70, 1, 200, 2000 ) );
            light.shadow.bias = -0.000222;
            light.shadow.mapSize.width = 1024;
            light.shadow.mapSize.height = 1024;
            scene.add( light );
            spotlight = light;

            // scene.add( new THREE.CameraHelper( light.shadow.camera ) );
            //-------------------------------------------------------------
            //scene.add( new THREE.CameraHelper( light.shadow.camera ) );

            var planeGeometry = new THREE.PlaneGeometry( 2000, 2000 );
            planeGeometry.rotateX( - Math.PI / 2 );
            var planeMaterial = new THREE.ShadowMaterial();
            planeMaterial.opacity = 0.2;

            var plane = new THREE.Mesh( planeGeometry, planeMaterial );
            plane.position.y = -200;
            plane.receiveShadow = true;
            scene.add( plane );

            var helper = new THREE.GridHelper( 2000, 100 );
            helper.position.y = - 199;
            helper.material.opacity = 0.25;
            helper.material.transparent = true;
            scene.add( helper );

            var axis = new THREE.AxisHelper();
            axis.position.set( -500, -500, -500 );
            scene.add( axis );



            renderer = new THREE.WebGLRenderer( { antialias: true } );

            renderer.setClearColor( 0xf0f0f0 );
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( window.innerWidth, window.innerHeight );
            renderer.shadowMap.enabled = true;

            container.appendChild( renderer.domElement );


            stats = new Stats();

            container.appendChild( stats.dom );

and so far etc...

these codes doesn't work:

        stats = new Stats();

container.appendChild( stats.dom );

I use in gitshell : browserify input.js | indexhtmlify > output.html so what should I do? so the browser(chrome) is blank page.



via hasanbaghal

Sequelizejs produces wrong column name for Foreign Key in insert query with belongsTo relationship

I have a sequelize model for Organisation table in PostgreSQL dialect.

'use strict';
module.exports = function(sequelize, DataTypes) {
  var Organisation = sequelize.define('Organisation', {
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    }, 
    type: {
      type: DataTypes.INTEGER,
      allowNull: false,
    },
    numUsers: {
      type: DataTypes.INTEGER,
      allowNull: false,
    },
    expDate:  {
      type: DataTypes.DATE,
      allowNull: false
    }
  }, {
    classMethods: {
      associate: function(models) {
        Organisation.belongsTo(models.User);
      }
    }
  });
  return Organisation;
};

And another model called Users for Users Table:

'use strict';


module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
    passwordHash: DataTypes.STRING,
    passwordResetToken: DataTypes.STRING
  },
  {
    classMethods: {
      associate: function(models) {

        User.belongsTo(models.Organisation);
      }
    }
  });
  return User;
};

When I create a User with Organisation in a REST API like this:

DB.User.create({
      name: attributes.primaryContactName,
      email: attributes.primaryContactEmail,
      role: 10,
      Organisation: {
        name: attributes.name,
        type: 1,
        numUsers: attributes.numUsers,
        expDate: attributes.expDate
      }
    }, {
      include: DB.Organisation
    }).then(user => {
      return user.Organisation.update({ userId: user.id })
    }).then(org => {
      res.json(org);
    }).catch(next); 
  }).catch(next);

It gives me an error "column \"OrganisationId\" of relation \"Users\" does not exist". The insert query generated by SequelizeJS is:

INSERT INTO "Users" ("id","name","email","role","createdAt","updatedAt","OrganisationId") VALUES (DEFAULT,'vbvb','cdcd.pro@gmail.com',10,'2017-04-23 05:17:30.035 +00:00','2017-04-23 05:17:30.035 +00:00',20)

Obviously the "OrganisationId" does not exist in my table. The column name that exists is "organisationId". However, as per documentation for Sequelize its written that the default foreign key will be camelCased but in my case, its not camelCasing for Insert.



via Anil Konsal

render pharse in three.js javascript file doesn't work

this phrase in three.js javascript file in my code doesn't work:

            renderer = new THREE.WebGLRenderer( { antialias: true } );

            renderer.setClearColor( 0xf0f0f0 );
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( window.innerWidth, window.innerHeight );
            renderer.shadowMap.enabled = true;

            container.appendChild( renderer.domElement );

I have codes like this :

        function init() {


            container = document.getElementById( 'container' );

            scene = new THREE.Scene();
            camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
            camera.position.set( 0, 250, 1000 );
            scene.add( camera );

            scene.add( new THREE.AmbientLight( 0xf0f0f0 ) );
            var light = new THREE.SpotLight( 0xffffff, 1.5 );
            light.position.set( 0, 1500, 200 );
            light.castShadow = true;
            light.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 70, 1, 200, 2000 ) );
            light.shadow.bias = -0.000222;
            light.shadow.mapSize.width = 1024;
            light.shadow.mapSize.height = 1024;
            scene.add( light );
            spotlight = light;

            // scene.add( new THREE.CameraHelper( light.shadow.camera ) );
            //-------------------------------------------------------------
            //scene.add( new THREE.CameraHelper( light.shadow.camera ) );

            var planeGeometry = new THREE.PlaneGeometry( 2000, 2000 );
            planeGeometry.rotateX( - Math.PI / 2 );
            var planeMaterial = new THREE.ShadowMaterial();
            planeMaterial.opacity = 0.2;

            var plane = new THREE.Mesh( planeGeometry, planeMaterial );
            plane.position.y = -200;
            plane.receiveShadow = true;
            scene.add( plane );

            var helper = new THREE.GridHelper( 2000, 100 );
            helper.position.y = - 199;
            helper.material.opacity = 0.25;
            helper.material.transparent = true;
            scene.add( helper );

            var axis = new THREE.AxisHelper();
            axis.position.set( -500, -500, -500 );
            scene.add( axis );


            renderer = new THREE.WebGLRenderer( { antialias: true } );

            renderer.setClearColor( 0xf0f0f0 );
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( window.innerWidth, window.innerHeight );
            renderer.shadowMap.enabled = true;

            container.appendChild( renderer.domElement );

            stats = new Stats();
            container.appendChild( stats.dom );

            var gui = new dat.GUI();
            gui.add( params, 'uniform' );
            gui.add( params, 'tension', 0, 1 ).step( 0.01 ).onChange( function( value ) {
                splines.uniform.tension = value;
                updateSplineOutline();
            });
            gui.add( params, 'centripetal' );
            gui.add( params, 'chordal' );
            gui.add( params, 'addPoint' );
            gui.add( params, 'removePoint' );
            gui.add( params, 'exportSpline' );
            gui.open();

            // Controls
            controls = new THREE.OrbitControls( camera, renderer.domElement );
            //controls = new OrbitControls( camera, renderer.domElement );
            controls.damping = 0.2;
            controls.addEventListener( 'change', render );

            transformControl = new THREE.TransformControls( camera, renderer.domElement );
            //transformControl = new TransformControls( camera, renderer.domElement );
            transformControl.addEventListener( 'change', render );

            scene.add( transformControl );

and so far etc...



via hasanbaghal

How to bulk update mysql rows

I had successful bulk insert rows into database by passing array of the objects into database. When comes to update, it doesn't work that way either.

Bulk Insert

var photos_array = [];
req.body.photos.forEach(function(photo){
  photos_array.push([photo.menu_id, photo.name, photo.url])
})
connection.query('INSERT INTO ' + dbconfig.database + '.' + dbconfig.photos_table + ' (menu_id, name, url) VALUES ?', [photos_array], function(err, result){
  if(result.affectedRows > 0){}
  else{}
});

How to do bulk insert with a single query without multiple statements on MySQL? The reason I don't want to allow multiple statements on my codes is because to prevent SQL injection attacks. Or you have another better approaches are much more faster and secure, will be appreciated.



via Foonation

FedEx Rate Request with node.js using node-soap

I'm trying to make a simple rate request to the FedEx API using node-soap. I've read through the documentation and the WSDL to include all the required information but all I get is an empty object as response.

Since I'm not getting any errors I'm not sure what I'm doing wrong or if I'm missing some step.

Here's my code:

var express = require('express');
var app = express();
var port = process.env.PORT || 7000;
var path = require('path');
var soap = require('soap');

var url = path.join(__dirname, 'wsdl', 'RateService_v20.wsdl');

var params = {
      WebAuthenticationDetail: {
        UserCredential: {
          Key: 'the key I was given by FedEx',
          Password: 'the password I was given'
        }
      },
      ClientDetail: {
        AccountNumber: 'the acc number I was given',
        MeterNumber: 'the meter number I was given',
        Localization: {
            LanguageCode: 'EN'
        }
      },
      Version: {
        ServiceId: 'crs',
        Major: '20', 
        Intermediate: '0',
        Minor: '0'
      },
      RateRequest: {  
        ReturnTransitAndCommit: true,
        RequestedShipment: {
            DropoffType: 'REGULAR_PICKUP',
            PackagingType: 'FEDEX_10KG_BOX',
            RateRequestTypes: 'LIST',
            PackageCount: '1',
            Shipper: {
                Contact: {
                    PersonName: 'Sender Name',
                    CompanyName: 'Company Name',
                    PhoneNumber: '5555555555'
                },
                Address: {
                    StreetLines: [
                    'Address Line 1'
                    ],
                    City: 'Collierville',
                    StateOrProvinceCode: 'TN',
                    PostalCode: '38017',
                    CountryCode: 'US'
                }
            },
            Recipient: {
                Contact: {
                    PersonName: 'Recipient Name',
                    CompanyName: 'Company Receipt Name',
                    PhoneNumber: '5555555555'
                },
                Address: {
                    StreetLines: [
                    'Address Line 1'
                    ],
                    City: 'Charlotte',
                    StateOrProvinceCode: 'NC',
                    PostalCode: '28202',
                    CountryCode: 'US'
                }
            }
        }
    }
};

app.get('/describe',function(req,res){
    soap.createClient(url, function(err, client) {
        if (err) throw err; 
        res.send(client.describe());
    });
});

app.get('/test',function(req,res){
    soap.createClient(url, function(err, client) {
        if (err) throw err; 
        client.RateService.RateServicePort.getRates(params, function(err, result) {
          res.send(result);
      });
    });
})

app.listen(port, function(){
    console.log('app listening on port '+ port);
})



via Matheus Alves

How do I get the server timestamp in firebase functions?

I know you can pull the server timestamp in web, ios, and android - but what about the new firebase functions? I can't figure out how to get the server timestamp there? Use case is me wanting to timestamp an email when it arrives.

On web it is Firebase.database.ServerValue.TIMESTAMP

But that doesn't seem to be available in the functions node server interface?

I think it is late and I may be missing the point here...



via Justin Handley

OSX cannot open the `chrom://` protocol by the `open` command

when I try to edit

open "chrome://settings"

It says: The file /chrome:/settings does not exist.

open -a Google\ Chrome "chrome://settings"

also couldn't open the settings in chrome.seems the open command only could open the http && https protocol

In fact, I want to debug some Node code in Chrome Dev Tool, every time I run

node --inspect --debug-brk index.js

I must copy the debug link into Chrome to open the Dev Tool. I want to open it automatically.But the open command cannot it.So want to ask for help.



via Loatheb

Need value from callback to be accessible in entire file

Relevant posts already exist but I couldn't figure out how to apply the principles to my situation.

I need the function to return the returnVal as modified within the callback (which obviously doesn't work - returns false every time).

Any ideas?

function login(user){
  var returnVal = false;
  User.findOne({username: user.username}, function (err, res){
    res.comparePassword(user.password, function(err, isMatch) {
      if (err) throw err;
      if(isMatch){
        returnVal = true;
      }
    });
  });
  return returnVal;
}

Thank you!



via Martin Stuessy

Knex (Bookshelf) transaction with semantic errors

Given I have a large transaction needing to be performed, I'd like to know exactly which part of the query failed. For example, if the second insert in a series of inserts failed, I'd like to provide a semantic error for error logging. Is there any way to achieve this sort of functionality?

Here's the example from Knex's docs and I've only been able to have the single catch block which generally catches any failure within a promise chain (if I understand correctly).

knex.transaction((trx) => {

  const books = [
    { title: 'Canterbury Tales' },
    { title: 'Moby Dick' },
    { title: 'Hamlet' }
  ];

  return trx
  .insert({ name: 'Old Books' }, 'id')
  .into('catalogues')
  .then((ids) => {
    return Promise.map(books, (book) => {
      book.catalogue_id = ids[0];
      return trx.insert(info).into('books');
    });
  });
})
.then((inserts) => {
  console.log(inserts.length + ' new books saved.');
})
.catch((error) => {
  // If we get here, that means that neither the 'Old Books' catalogues insert,
  // nor any of the books inserts will have taken place.
  console.error(error);
});



via Detuned

Page crashes after 5 ajax posts

I'm using NodeJs and Jquery for my site which allows users to log in and post text to their dashboard. The way this works is when the user hits the "/dashboard" route it sends all of the user's current posts to the html page, via templating.

Within the "/dashboard" the user can also post to "/dashing" and then I use ajax to render the lastest post. However, after posting 5 times the browser stops loading the content to the DOM. Upon further inspection in the Chrome Dev tools > Network it looks like after 5 posts the posts after that are all pending.

How can I fix this?



via Moe Chughtai

Missing parents error while broadcasting btc transaction

My code is as follows for a simple script to generate raw transactions.

var path = require('path').dirname(require.main.filename)
var bitcore = require('bitcore-lib')
var fs = require('fs')
var UnspentOutput = bitcore.Transaction.UnspentOutput
const blockchain = require('blockchain.info')

var json = fs.readFileSync(path + '/' + '1MPP77eCzAsCKMjtWzdcNw4XMUxb5ePBeA.json');
obj = JSON.parse(json)

var address = "1C3xRrMetAdz2VSnbuDTnwHj3Dyeo9auk2"
var amount = 1000000 //satoshis
var privkeySet = bitcore.PrivateKey.fromWIF(obj["priv"]);
var cAddr = "1MPP77eCzAsCKMjtWzdcNw4XMUxb5ePBeA"

blockchain.blockexplorer.getUnspentOutputs(cAddr).then(outputs => {
  var utxo = new UnspentOutput({
    "txid" : outputs['unspent_outputs'][0]['tx_hash'],
    "vout" : outputs['unspent_outputs'][0]['tx_output_n'],
    "address" : cAddr,
    "script" : outputs['unspent_outputs'][0]['script'],
    "satoshis" : outputs['unspent_outputs'][0]['value']
  })

  var utxos = [utxo]

  var tx = new bitcore.Transaction()
    .from(utxos)
    .to(address, amount)
    .change(cAddr)
    .fee(10000)
    .sign(privkeySet);

  console.log("transaction = " + tx.verify());
  console.log("Signature = " + tx.isFullySigned());

  console.log(tx)
});

However, when I broadcast the raw transaction via blockchain.info, I get the following...

Missing parents for 62ce2eacfb96368dc7751e023d0890eae2e700c46dce1bd91192be27db6e97e7 while inserting: [872f22da56a21f500b87db1a6361ca228cca6b75913faeb4cb9ce2d19133a185]

Both verify and isFullySigned return true. The raw transaction is as follows...

010000000185a13391d1e29ccbb4ae3f91756bca8c22ca61631adb870b501fa256da222f87000000006b483045022100d713fbef655d7962731cc672b84a29db25fb274494a783f0d6507a683fd91301022044881127ec59d291d7f0dcf12bc7163be5bcf0d64808d5e8f5fac897e0c40d9401210327efda0447312e9bf7daff4788aa721302cc14778bcbdfb4e679229e985357b9ffffffff0240420f00000000001976a91479387c223f297cad674c523bd44403c1caf666ca88ac7ae90300000000001976a914df9e1e985d57beaafa44c6cafe712f05cddc2db188ac00000000

Absolutely no idea what's going wrong. Transaction is signing, the unspent output is good, etc. Any help is appreciated, thanks!



via Zenzile

Video is not see running the helloworld node js samples , KMS 6.0 ,Ubuntu 14.04

Running helloworld nodejs sample on the KurentoMedia Server 6.0 , Ubuntu14.04.

start the hello world(chrome,firefox) and run on start.No video is displayed in local and remote , just the spinning wheels .

The log on the Browser window shows the following : Page loaded ... Starting video call ... Creating WebRtcPeer and generating local sdp offer ... spec: {"audio":true,"video":{"width":640,"framerate":15}} chrome: {"audio":true,"video":{"optional":[{"minWidth":640},{"maxWidth":640},{"minFramerate":15},{"maxFramerate":15}]}} Invoking SDP offer callback function localhost:8443 Senging message: ..............

Received message: {"id":"iceCandidate","candidate":{"candidate":"candidate:8 2 TCP 1019216638 192.168.153.128 9 typ host tcptype active","sdpMid":"audio","sdpMLineIndex":0,"module":"kurento","type":"IceCandidate"}} Received message: {"id":"iceCandidate","candidate":{"candidate":"candidate:8 2 TCP 1019216638 192.168.153.128 9 typ host tcptype active","sdpMid":"video","sdpMLineIndex":1,"module":"kurento","type":"IceCandidate"}} Received message: {"id":"iceCandidate","candidate":{"candidate":"candidate:9 2 TCP 1015022334 192.168.153.128 37115 typ host tcptype passive","sdpMid":"audio","sdpMLineIndex":0,"module":"kurento","type":"IceCandidate"}} Received message: {"id":"iceCandidate","candidate":{"candidate":"candidate:9 2 TCP 1015022334 192.168.153.128 37115 typ host tcptype passive","sdpMid":"video","sdpMLineIndex":1,"module":"kurento","type":"IceCandidate"}}

How to verify if the audio/vedio is transmitting. Any suggestion is welcome.



via Raghav

How does the @shopify/polaris project get built from github repo to npm dependency?

I'm interested in learning how the @shopify/polaris project in github is built and published to npm. My main questions are:

  • How are the index.es.js and index.js files being generated? Are those being generated programmatically on my computer, or are they published to npm like this?
  • What mechanism is preventing the files in the github repo from being downloaded when installed? I don't see a .npmignore in the repo.

Below I have the files in the npm package, and the github, and you can see they're different.

Here's what the polaris project looks like when it's installed via NPM / yarn.

.
├── CHANGELOG.md
├── README.md
├── index.es.js
├── index.js
├── package.json
├── src
├── styles
├── styles.css
├── styles.scss
└── types

Here's what the project looks like on github.

.
├── CHANGELOG.md
├── README.md
├── circle.yml
├── config
├── documentation
├── examples
├── package.json
├── scripts
├── src
├── tests
├── tsconfig.json
├── tslint.json
└── yarn.lock



via ThomasReggi

SignaturePad not defined - can not initialise signature_pad module into script

I'm having an issue using the npm module - signature_pad, and can't seem to get it set up. At the moment all I am using is vanilla HTML, CSS and JS. At the moment I keep getting an error saying: SignaturePad is not defined. I tried importing the module from my package.JSON file using import SignaturePad from 'signature_pad' but I get an error back saying unexpected token import.

I have attached my HTML and JS code below. Any suggestions?

JavaScript

    var wrapper1 = document.getElementById("signature-pad-1"),
        canvas1 = wrapper1.querySelector("canvas"),
        signaturePad1;

        resizeCanvas(canvas1);
        signaturePad1 = new SignaturePad(canvas1);

        function resizeCanvas(canvas) {
           var ratio =  window.devicePixelRatio || 1;
           canvas.width = canvas.offsetWidth * ratio;
           canvas.height = canvas.offsetHeight * ratio;
           canvas.getContext("2d").scale(ratio, ratio);
       }

HTML

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Sign Here</title>
        <link rel="stylesheet" href="main.css">
      </head>
      <body>
        <div class="contract">
          <h1>Signature Below</h1>
          <p>ABC</p>
          <div id="signature-pad-1" class="m-signature-pad">
            <div class="m-signature-pad--body">
              <canvas></canvas>
            </div>
          </div>
          <script type="text/javascript" src="./js/sig_pad.js"></script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/signature_pad/1.5.3/signature_pad.min.js"></script>
      </body>
    </html>



via Todd Drinkwater

Framework Advice

I have a site that was done in CakePHP but I want to redevelop to give it a fresher feel.

The object of the site is to create a document the user can download or email to themselves. The user will select options from drop down menus from data stored in the db, the user is given many forms and options in about 5 steps, and the end product is a file (which I would like to be in word, pdf, txt...something the user will select).

The user will also have the option to select the look of their document from various layouts.

Main functionality required is the ability to spell check, create preview, create document in various formats.

Thanks for advice!



via BizBrar

Node crashes - TypeError: callback is not a function

I have the following code. Whenever the code reaches that it needs to return a callback I get the following error:

TypeError: callback is not a function

This is my code:

exports.myCoolOperation = function(myParam, callback) {

  var mod_datastore = require('@google-cloud/datastore')({
    projectId: params.GAE_PROJECTID,
    keyFilename: params.GAE_KEYFILE
  });

  var myLibrary = include('lib/myLibrary');

  myLibrary.doSomething(myParam, function(err, result) {
    if (err) {
      //Server crashes here with TypeError: callback is not a function      
      return callback('error');
    } else {
      if (result) {

        var transaction = mod_datastore.transaction();

        transaction.run(function(err) {
          if (err) {
            //Server crashes here with TypeError: callback is not a function  
            return callback('error');
          }

          transaction.save([{
            key: mod_datastore.key(['myTable', myParam]),
            method: 'insert',
            data: {
                name: 'date',
                value: 'Todays date'
              });

          transaction.commit(function(err, apiResponse) {
            if (!err) {
             //Server crashes here with TypeError: callback is not a function
              return callback(null, 'Everything is cool');
            }

            //Server crashes here with TypeError: callback is not a function
            return callback('error');
          });


        });

      } else {
        return callback('error');
      }
    }

  });
}

I am calling this module like so:

myModule.myCoolOperation(req.body.myparam, function (err, result) {
        if (err) {
            return next(err);
        } else {
            return res.status(200).json({res: result});
        }
    });



via user2924127

How to parse a JSON.Stringfy?

Allow me to preface this by saying that I did look at both .parse and how to make it work with .stringify, but nothing worked.

In my code, based on what IBM has for its natural language processing (https://www.ibm.com/watson/developercloud/natural-language-understanding/api/v1/?node#post-analyze) I have the following part:

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');

var natural_language_understanding = new NaturalLanguageUnderstandingV1({
  'username': 'f3550111-bd50-4e5f-8d44-8f0cc493c05e',
  'password': 'XSG0rEW0UOlB',
  'version_date': '2017-02-27'
});


var parameters = {
  'text': 'A most interesting and amusing text indeed, about as amusing as IBMs godawful documentations',

  'features': {
    'entities': {
      'emotion': true,
      'sentiment': true,
      'limit': 2
    },
    'keywords': {
      'emotion': true,
      'sentiment': true,
      'limit': 2
    }
  }
}

I stringify the response per the example code as follows:

function calculateSentiment() {

    natural_language_understanding.analyze(parameters, function(err, data) {
        if (err)
            console.log('error:', err);
        else {
            var myData = JSON.stringify(data, null, 2);
            //console.log(myData[0][0][0]);
            //var json = JSON.stringify(JSON.parse(data));
            //console.log("Score: " + json);

            //var prsed = (JSON.parse(data));
            console.log("Parsed: " + myData);
            }
        }
    ); 
}

As you can see, I have all those comments which were my attempts at parsing. If I just have it print the data all I get is [object Object]. How can I properly parse this data? The corresponding result of the stringify is (the "Parsed: " part is from my own console output):

Parsed: {
  "keywords": [
    {
      "text": "amusing text",
      "sentiment": {
        "score": 0.768903
      },
      "relevance": 0.98388,
      "emotion": {
        "sadness": 0.260734,
        "joy": 0.407077,
        "fear": 0.113361,
        "disgust": 0.006258,
        "anger": 0.028386
      }
    },
    {
      "text": "IBMs godawful documentation",
      "sentiment": {
        "score": 0
      },
      "relevance": 0.809662,
      "emotion": {
        "sadness": 0.156867,
        "joy": 0.412954,
        "fear": 0.094685,
        "disgust": 0.082537,
        "anger": 0.101907
      }
    }
  ],
  "entities": [],
  "language": "en"
}
Parsed: {
  "keywords": [
    {
      "text": "amusing text",
      "sentiment": {
        "score": 0.768903
      },
      "relevance": 0.98388,
      "emotion": {
        "sadness": 0.260734,
        "joy": 0.407077,
        "fear": 0.113361,
        "disgust": 0.006258,
        "anger": 0.028386
      }
    },
    {
      "text": "IBMs godawful documentation",
      "sentiment": {
        "score": 0
      },
      "relevance": 0.809662,
      "emotion": {
        "sadness": 0.156867,
        "joy": 0.412954,
        "fear": 0.094685,
        "disgust": 0.082537,
        "anger": 0.101907
      }
    }
  ],
  "entities": [],
  "language": "en"
}
Parsed: {
  "keywords": [
    {
      "text": "amusing text",
      "sentiment": {
        "score": 0.768903
      },
      "relevance": 0.98388,
      "emotion": {
        "sadness": 0.260734,
        "joy": 0.407077,
        "fear": 0.113361,
        "disgust": 0.006258,
        "anger": 0.028386
      }
    },
    {
      "text": "IBMs godawful documentation",
      "sentiment": {
        "score": 0
      },
      "relevance": 0.809662,
      "emotion": {
        "sadness": 0.156867,
        "joy": 0.412954,
        "fear": 0.094685,
        "disgust": 0.082537,
        "anger": 0.101907
      }
    }
  ],
  "entities": [],
  "language": "en"
}



via SomeStudent

npm init permission denied

I'm currently doing an online course in coding and when following along the instructions I've run into a problem. while pushing the project to github i get this error when I run npm init

Error: EACCES: permission denied, mkdir '/user'
at Error (native)
TypeError: Cannot read property 'get' of undefined
at writeLogFile (/usr/local/lib/node_modules/npm/lib/utils/error-handler.js:205:32)
at exit (/usr/local/lib/node_modules/npm/lib/utils/error-handler.js:96:5)
at errorHandler (/usr/local/lib/node_modules/npm/lib/utils/error-handler.js:194:3)
at /usr/local/lib/node_modules/npm/bin/npm-cli.js:76:20
at cb (/usr/local/lib/node_modules/npm/lib/npm.js:195:22)
at /usr/local/lib/node_modules/npm/lib/npm.js:233:24
at /usr/local/lib/node_modules/npm/lib/config/core.js:81:7
at Array.forEach (native)
at /usr/local/lib/node_modules/npm/lib/config/core.js:80:13
at f (/usr/local/lib/node_modules/npm/node_modules/once/once.js:25:25)

I'm quite new to all this so newbie explanation would be really appreciated =P

Thanks!!



via Callum Pullinger

How node.js single thread model process concurrent request?

Two concurrent request R1 and R2 comes to node.js server. Node.js is running with single thread T1. T1 takes 5 seconds to process the request R1. Assume this time spent in some actual processing of big function and there is no waiting/IO call .

My question is - will request R2 will be taken up by after 5 seconds(once R1 completes) or both(R1 and R2) will be run in round robin fashion ?



via user3198603

why is the nodejs event loop non-deterministic after the first run?

Node.js doc says:

The order in which the timers are executed will vary depending on the context in which they are called. If both are called from within the main module, then timing will be bound by the performance of the process (which can be impacted by other applications running on the machine).

For example, if we run the following script which is not within an I/O cycle (i.e. the main module), the order in which the two timers are executed is non-deterministic, as it is bound by the performance of the process:

// timeout_vs_immediate.js
setTimeout(function timeout () {
 console.log('timeout');
},0);

setImmediate(function immediate () {
  console.log('immediate');
});

$ node timeout_vs_immediate.js
timeout
immediate

$ node timeout_vs_immediate.js
immediate
timeout

From the same page I think I understand how the event loop works, but after this main run, why can the even loop not fulfill its job correctly ? What's so different there than within an I/O cycle ?



via fabmlk

How to catch TCP socket transmission failures in Node.JS?

When I write data to a TCP socket in Node, which is not closed but the client on the other side is not connected anymore (because of network failure for example), how do I know?

The socket's error event doesn't fire in this case for me. If I'm right, TCP gives up sending data, if there is absolutely no ACK packets from the other side, doesn't it? Or am I misunderstanding something?



via KisGabo

How to remove the "Connected to BrowserSync" badge from lite-server in the browser

I've installed the John Papa's lite-server NPM package via VS Code console and it's working. But, how can I remove the "Connected to BrowserSync" badge that appears in the browser every time a save a file - and it reloads the file automatically in the browser?



via mundozaneti

Constructor is not called during instantiation of imported class

When I was trying to write some unit tests for ECMAScript6 class, I encoutered following problem: constructor is not being called during imported class instantiation.

I quickly found out that it is some behaviour of Babel + node.js I just can't understand. Here is the smallest piece of code showing the problem:

// dummy.js
export class Dummy {
    construct(){
        this.value = 1
    }
    set(value){
        this.value = value
    }
}

 

// main.js
require("babel-register")({
    presets: [
        "es2015" 
    ],
});

var Dummy = require('./dummy.js').Dummy

var d = new Dummy()
console.log(d.value) // undefined, should be 1

d.set(13)
console.log(d.value) // 13

It really confuses me, because method set() works as expected. Originally I got such weird behaviour with ES6 import statement, however I couldn't use it here as node.js does not support it. As You can see we get the same problem with require.

I use node v6.10 and babel v6.24.



via reidar13

Error 401 in windows command prompt?

When use npm run dev, which scripts the "node app.js" to run. But when I try to run it, I get this error code:

C:\Users\rfasc\Dropbox\Hackathon\HackCuTwitter>npm run dev

> Tweeter@1.0.0 dev C:\Users\rfasc\Dropbox\Hackathon\HackCuTwitter
> node app.js

Error: Status Code: 401
    at Request.<anonymous (C:\Users\rfasc\Dropbox\Hackathon\HackCuTwitter\node_modules\twitter\lib\twitte
 r.js:274:28)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
    at Request.onRequestResponse (C:\Users\rfasc\Dropbox\Hackathon\HackCuTwitter\node_modules\request\request.js:
 1074:10)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at HTTPParser.parserOnIncomingClient [as onIncoming] 
(_http_client.js:473:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
    at TLSSocket.socketOnData (_http_client.js:362:20)
    at emitOne (events.js:96:13)

I also get this error when I try to run sudo at all when I use bash in the cmd:

ryryfasch@LAPTOP-9TPB1OJ6:/mnt/c/Users/rfasc/Dropbox/Hackathon/HackCuTwitter$ sudo i
sudo: unable to resolve host LAPTOP-9TPB1OJ6

I have tried looking up many fixes and can't figure it out. Thanks.



via Ryan Fasching

Node.js server hangs occasionally

I have this node.js server. The problem is sometimes I notice that it gets stuck. That is the client can make requests, but the server doesn't respond, rather it doesn't end the response, it just gets stuck in the server side. If I look in client side dev tools on the http request, it has a gray circle icon meaning waiting for server response. Even if I wait 10 minutes, nothing happens.

The server side also writes things to console on the requests, which doesn't happen when it gets stuck. On the node.js console, if I then press ctrl+c when it got stuck, I then suddenly see all the console.log messages just appear on the console, and at the same time, the dev tools, recieves all the responses from the server side, i.e. the gray circle changes to green.

Does anyone know what this problem is?

Thanks

var express = require('express');
var https = require("https");
var fse = require("fs-extra");
var bodyParser = require('body-parser');

// INFO

var root = __dirname + '/public';

setUpServer();

// SET UP SERVER

function setUpServer() {
    var app = express();

    app.use(express.static(root));
    app.use(bodyParser.urlencoded({ extended: false }))

    app.get('/', function (req, res) {
        var dest = 'index.html';
        res.sendFile(dest, { root: root + "/pong" });
    });
    app.post('/get_brain', function (req, res) {
        res.end("1");
        console.log('Sent master brain to a client!');
    });
    app.post('/train_and_get_brain', function (req, res) {
        res.end("1");
        console.log('Sent master brain to a client!');
    });



    var privateKey  = fse.readFileSync('sslcert/key.pem', 'utf8');
    var certificate = fse.readFileSync('sslcert/cert.pem', 'utf8');
    var credentials = {key: privateKey, cert: certificate};

    var httpsServer = https.createServer(credentials, app);
    httpsServer.listen(process.env.PORT || 3000, function () {
        var host = httpsServer.address().address;
        var port = httpsServer.address().port;

        console.log('AI started at https://%s:%s', host, port);
    });
}



via omega

404 not found error while using AJAX and Node.js

I'm looking to gather JSON data from the Open Weather Map API but have been running into trouble.

First, while running it using "file:///" I received a "Cross origin requests are only supported for protocol schemes..." error. Previous answers suggested running on a local server so I spun up a local node server and ran it again but received a "Get http://8080/404/url 404 not found" error.

Fairly new to all of this so any suggestions would be greatly appreciated.

var $url = "api.openweathermap.org/data/2.5/weather?";
$url += $.param({
  "q": "London",
  "units": "imperial",
  "appid": "6cbde47ec63b876312c74a78055a5481",
  "format": "json",
  "callback": "?"
});

$.ajax({
url: $url,
dataType: "jsonp",
  success: function(data) {
    console.log("Working");
}
});



via pxr13

MongoDB Range Issue

I'm using nodejs and mongodb. I want to search docs between a num range but the function allways give me number that outside the range. For example, this is my function and I want to get the results of the docs that they has a field size with the numbers between 1 to 1200:

                            db.collection(example).find({
                                size: {
                                    "$gte": 1,
                                    "$lte": 1200
                                }
                            }).toArray(function (err, results) {
                                db.close();
                                console.log("results="+results);
                            });

thanks anyway :)



via RandomGuy17

is mongo stored javascript good solution to multiple DB inserts in nodejs

I have a functionality is Mean Stack which has multiple collection inserts and creation. If it do that in plain mongoose , its going to be multiple Mongo calls and it might be slow. Can i use mongo stored javascript for this?Pass some values to mongo javascript and it can do all the things from there.. Is it a suggested approach?



via Jocket

How to call a mixin in Jade that is being displayed in a Node/Express route

I'm trying to create a component that I'll be putting on a website many times using a Jade template.

My route looks like this:

router.get('/', function(req, res, next) {
    res.render('indicators',{category:"", number:"1", title:"whatever"});
});

indicators.jade:

extends layout

mixin indicator(category, number, title)
  div.dataEntryBlock
    div.number
        div.center.number #{number}
    div.dataEntryTitle #{title}


body
    block content
        +indicator(#{category}, #{number}, #{title})

But I get Unexpected token ILLEGAL on this line +indicator(#{category}, #{number}, #{title}) when I go to the route. Isn't this how I'm supposed to call a mixin?



via Glen Pierce

npm gulp 800a138f javascript error

When i put 'gulp hello' in cmd i got this error 800a138f javascript object expected error

This is my package.json file

`{
 "name": "goes",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
    "start": "node gulp.js"
 },
"author": "",
"license": "ISC",
"devDependencies": {
    "gulp": "^3.9.1"
  }
 }`

This is gulp.js

 `var gulp = require('gulp');
 gulp.task('hello', function() {
 console.log('Hello Zell');
 });`



via Edmund Muskie

authentication of user using nodejs+express+passport local strategy and new angular

I have followed every blog which describe how to use local strategy with passport running on express. the users data sits on mysql, and i have created the server code

let express = require('express')
let bodyParser = require('body-parser');
let path = require('path');
let app = express()
let cors = require('cors');
let passport = require('passport');
let flash = require('connect-flash');

let morgan = require('morgan');
let cookieParser = require('cookie-parser');
let session = require('express-session');


app.use(morgan('dev')); // log every request to the console

app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: false }))

app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-
   With, Content-Type, Accept");
   next();
});



app.use(cors());
app.use('/', express.static(path.join(__dirname, 'public')));

app.use(session({
   secret: 'secretme',
   resave: true,
   saveUninitialized: true
})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in 
      session

require('./config/passport')(passport); // pass passport for 
       configuration

function isAuthenticated(req, res, next) {

    //if (req.user && req.user.authenticated)
    //    return next();
    if (req.isAuthenticated())
        return next();

    res.status(401).send()
}

app.get('/api/about', isAuthenticated, (req, res) => {
    res.json({
        version: '1.1'
    })
})

the login pass ok, this is the function:

 app.post('/api/login', passport.authenticate('local-login', {
failureRedirect: '/bad-login',
failureFlash: true // allow flash messages
}), (req, res) => {
     res.status(200).send();
})

regarding the client side, I am using Angular v4 , the login call pass ok

login(email: string, password: string) {
  var headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');
  let options = new RequestOptions({
    headers: headers
  })
  let data = new URLSearchParams();
  data.append('email', email);
  data.append('password', password);
  let body = data.toString()
  return  this._http.post(`http://X.X.X.X/api/login`, body, options)
  .toPromise()
  .then(response => response.status)
}

how ever when I call the about api , I am getting 401. What did i missed?

about(): Promise<About> {
    return this._http.get(`http://X.X.X.X/api/about`, { withCredentials: true })
    .toPromise()
    .then(response => response.json() as About)
}



via li-raz

Why is node giving me this error?

i've been trying to make my first twitter bot, but when I run npm run dev I get this error:

> Tweeter@1.0.0 dev /mnt/c/Users/rfasc/Dropbox/Hackathon/HackCuTwitter
> node app.js

npm ERR! weird error 1
npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian

npm ERR! not ok code 0 

am somewhat new to using nodejs and the npm commmands to connect my code. Here is my package.json and my app.js file:

package.json:

{
  "name": "Tweeter",
  "version": "1.0.0",
  "description": "package.json tester",
  "main": "app.js",
  "dependencies": {
    "twitter": "^1.7.0",
    "twitter-stream-api": "^0.5.1"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "node app.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/kennychiwa/HackCuTwitter.git"
  },
  "author": "",
  "license": "BSD-2-Clause",
  "bugs": {
     "url": "https://github.com/kennychiwa/HackCuTwitter/issues"
  },
  "homepage": "https://github.com/kennychiwa/HackCuTwitter#readme"
}

and app.js:

var twitterpack = require('twitter');

var tokens {
  consumer_key: '-------9WJSaaqAe9yVvr30CF',
  consumer_secret: '-------------------fj3zoiZ2nUOTBWUjP4DqtGXIlzzbxbOY',
  token_key: '  ----------zNHmdL43N6RZJeOtJeH8ZhrursJUQlAqCycHqxbl',
  tokenk_secre: '----EcxAjUq1hLka2QYwSSZStETF7Mr2mBikHYCTTqodV'
}
var twitter = new twitterpack(tokens);

Twitter.stream('statuses/filter', {track: 'hey'}, function(stream) {

  stream.on('data', function(stream){

    console.log(tweet.text);
    var meanReply = {status: "hey @" + tweet.user.screen_name}
    Twitter.post('statuses/update', meanReply, function(error, tweetReply, 
response){
      if(error) {console.log(error) /*&&db.collection('errors', 
error.text)*/};
      console.log(tweetReply.text)}
     );


  });
   stream.on('error', function(error) {
   console.log(error);
  });
});

please help, thanks.



via Ryan Fasching

Trouble connecting to AWS Athena via JDBC using Node Lambda

I am trying to use AWS's JDBC Driver to allow a Lambda function running Node 6.10 to connect to AWS Athena and create a database. (I will also want to be able to create and query against tables inside of that databse).

I have tried the following code from an answer to a similar question:

var JDBC = require('jdbc');
var jinst = require('jdbc/lib/jinst');

if (!jinst.isJvmCreated()) {
  jinst.addOption("-Xrs");
  jinst.setupClasspath(['./AthenaJDBC41-*.jar']);
}

var config = {
  // Required 
  url: 'jdbc:awsathena://athena.us-east-1.amazonaws.com:443',
   // Optional 
  drivername: 'com.amazonaws.athena.jdbc.AthenaDriver',
  minpoolsize: 10,
  maxpoolsize: 100,
  properties: {
                s3_staging_dir: 's3://aws-athena-query-results-*/',
                log_path: '/logs/athenajdbc.log',
                user: 'access_key',
                password: 'secret_key'
   }
};


var hsqldb = new JDBC(config);

hsqldb.initialize(function(err) {
  if (err) {
    console.log(err);
  }
});

When I run this on my own machine (Mac OSX El Capitan 10.11.6), I see the popup pictured below with the message No Java runtime present, requesting install. printed to my console.

Popop

When I deploy my code to Lambda and run it there, it fails with the following message:

Error: /var/task/node_modules/java/build/Release/nodejavabridge_bindings.node: invalid ELF header

When run locally, I can see that things fail at the var hsqldb = new JDBC(config); line, but when running on Lambda, the error occurs immediately upon requiring JDBC (the first line of the code above).



via M Griest

Find key contain dot and replace with @

I have nested object which can have any number of key at any depth. I want to replace "." in all keys(if contain) with "@" How we can do this in efficient way.

Example Node js object

obj:{
        "BotBuilder.Data.SessionState": {
            "lastAccess": 1492886892545,
            "version": 14,
            "callstack": [
                {
                    "id": "*:/",
                    "state": {
                        "BotBuilder.Data.WaterfallStep": 0,
                        "BotBuilder.Data.Intent": "welcomeDialog"
                    }
                }
            ]
        }

Currently i am using hard coded solution , but any keys can be possible in object at any level which contain "." I want generalize way to solve this problem

My code :

replaceDot:function(doc){
    var finalobj={}
    var finaldata={}
    var finalcallstack=new Array();
    console.log("doc==>",doc)
    var callstack=doc["data"]["BotBuilder.Data.SessionState"]["callstack"]
    for(var i = 0; i < callstack.length; i++) {
        var tempcallstack={}
        if("BotBuilder.Data.WaterfallStep" in callstack[i]["state"]){
            tempcallstack["id"]=callstack[i]["id"]
            var tempstate={}
            tempstate["state"]=callstack[i]["state"]
            tempstate["state"]["BotBuilder@Data@WaterfallStep"]=tempstate["state"]["BotBuilder.Data.WaterfallStep"]
            tempstate["state"]["BotBuilder@Data@Intent"]=tempstate["state"]["BotBuilder.Data.Intent"]
            delete tempstate["state"]["BotBuilder.Data.WaterfallStep"]
            delete tempstate["state"]["BotBuilder.Data.Intent"]
            tempcallstack["state"]=tempstate["state"];
            finalcallstack.push(tempcallstack);
        }
        else{
            finalcallstack.push(callstack[i]);
        }
    }   
    var obj={}
    finalobj["lastAccess"]=doc["data"]["BotBuilder.Data.SessionState"]["lastAccess"]
    finalobj["version"]=doc["data"]["BotBuilder.Data.SessionState"]["version"]
    finalobj["callstack"]=finalcallstack;
    obj["BotBuilder@Data@SessionState"]=finalobj
    var secondrootobj={"BotBuilder@Data@SessionState":finalobj}
    return secondrootobj;
}



via Aakash Kag

Sorting objects based on a string value property in TypeScript

I have an array of objects and the definition for an object looks something like this:

export class AccountInfo {
  accountUid: string;
  userType: string;
  firstName: string;
  middleName: string;
  lastName: string;
}

NOTE: The reason I don't have userType as an enum is because the object is populated by a database call and I couldn't figure out a clean way to have the string returned from the db populate the enum.

I want to sort the array so that objects with a userType of 'STAFF' appear first, followed by 'TEACHER', then 'PARENT', then 'STUDENT'.



via TovrikTheThird

retrieve json array sent by android socket to node.js

how can this json object be retrieved in node.js. i tried socket.io and express, the connection is established but can not retrieve json object in node to save in database.

   JSONArray locAry = new JSONArray();
                        locAry.put(lat);
                        locAry.put(lon);
                        JSONObject obj = new JSONObject();
                        obj.put("coords",locAry);
                        obj.put("name",userPref.getString("user_name",""));
                        obj.put("id", userPref.getString("id",""));
                        obj.put("status", "0");
                        obj.put("type",userPref.getString("type",""));
                        obj.put("isdevice","1");

                        Common.socket.emit("Create Data", obj );
                        Common.socket.disconnect();



via babco Oshnouei

Unable to make app.post working using nodeJs

I am trying to connect my Angular2 to my nodeJs server. I have an authentification form which makes a post request. And I would like to use node to handle the post request. But so far I am unable to make my post request working. What I am missing?

This is my server.js which points to the folder dist in which i made the build of angular.

const express = require('express');
const path = require('path');
const http = require('http');

var walker = require('node-sync-walker');

const bodyParser = require('body-parser');


// Get our API routes
const api = require('./server/routes/api');

var app = express();

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

// Set our api routes
app.use('/api', api);

// Catch all other routes and return the index file
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

walker.routeWalker(__dirname + '/server/routes', app);

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));

This is my api.js

var users = [{username: "user", password: "password"}];

var router = require('express').Router();

module.exports = function(app) {
  router.post('/api/authenticate',
    function(req, res) {

      console.log("print something");

      let params = JSON.parse(req.body);

      // find if any user matches login credentials
      let filteredUsers = users.filter(user => {
          return user.username === params.username && user.password === params.password;
    });

      if (filteredUsers.length) {

        res.sendStatus(200);

      } else {
        console.log("print something else");

        return res.sendStatus(400)
      }

      //return;
    });
}



via edkeveked

Receiving net::ERR_EMPTY_RESPONSE with Nodejs Post Request

I'm trying to make a post request in my Node app; however, I am getting the following error.

OPTIONS http://localhost:27017/postDebate net::ERR_EMPTY_RESPONSE

How to resolve this?

Here is my route:

var express = require('express');
var router = express.Router();
var Debate = require('../models/debate');
var mdb = require('mongodb').MongoClient,
  ObjectId = require('mongodb').ObjectID,
  assert = require('assert');
var api_version = '1';
var url = 'mongodb://localhost:27017/debate';

router.post('/'+api_version+'/postDebate', function(req, res, next) {
  var debate = new Debate(req.body);
  console.log(debate, "here is the debate");
  debate.save(function(err) {
    if (err) throw err;
    console.log('Debate saved successfully!');
  });
  res.json(debate);
});

module.exports = router;

And since I am invoking this route after onclick calling a function in my ejs file, here is my javascript file.

function postDebate() {
  var topic = document.getElementById('topic').value;
  var tags = document.getElementById('tags').value;
  var argument = document.getElementById('argument').value;

  var debateObject = {
    "topic": topic,
    "tags": tags,
    "argument": argument
  };
  console.log(topic, tags, argument);

  $.ajax({
    type: 'POST',
    data: JSON.stringify(debateObject),
    contentType: "application/json",
        //contentType: "application/x-www-form-urlencoded",
        dataType:'json',
        url: 'http://localhost:27017/post',                      
        success: function(data) {
          console.log(JSON.stringify(data), "This is the debateObject");                               
        },
        error: function(error) {
          console.log(error);
        }
      });
}

How do I resolve this error? What is the problem here?

OPTIONS http://localhost:27017/postDebate net::ERR_EMPTY_RESPONSE



via Rohit Tigga

Node JS Stored Procedure field values returning as undefined

I am new to learning node, so sorry for a noob question. I have mysql running and stored proc returning fields. I want to assign the values to string variables and loop through each row. I do this alot in c#, but I am too much of a noob on node.

The results in the console are.

console.log(one)  -> 
[RowDataPacket {

CitySearchSearchEngineID: 1,

SearchURL: 'https://www.url.com' } ]

 OkPacket {

  fieldCount: 0,......
}

This above is good, however,

console.log(one.SearchURL); -> undefined

I have been struggling with this for a while now and can't figure out why I can't get the value out. I have tried a handful of different methods. If I do JSON.stringify it will give the row to a string just fine.

Any ideas would be appreciated.

Code below.

var db = mysql.createConnection({
   host: 'localhost',
   user: 'root',
   password: 'secretpassword',
   database: 'DB1',
   port: 3306
 });

 db.connect(function(err){
  if(err){
    console.log('Error connecting to Db');
    return;
  }
  console.log('Connection established');
});

db.query('CALL esp_Select_SearchURLs()', function(err, rows){
  if(err) throw err;

  _.each(rows, function(one){

    console.log(one);
    console.log(one.SearchURL);

  });
});



via StevenG

JSoup "HTTP error fetching URL. Status=404" when posting to NodeJS Server

I have a NodeJS server which functions correctly by itself (a user makes a POST request to http://localhost:3000/getGrades and a JSON object is returned containing data). The relevant code (from my server) to my issue is:

app.get('/getGrades', function (req, res) {
var cookies = {};
var username = req.headers.username;
var password = req.headers.password;
etc..........

Now, I am trying to do this POST request from a java program using JSoup:

try{
        Connection.Response res = Jsoup.connect("http://localhost:3000/getGrades")
                .header("username","USERNAME HERE")
                .header("password","PASSWORD HERE")
                .method(Connection.Method.POST)
                .execute();

        System.out.println("Res: " + res.toString());

    }catch (Exception e){System.out.print(e);}
}

However, I get the error:

org.jsoup.HttpStatusException: HTTP error fetching URL. Status=404, 
URL=http://localhost:3000/getGrades
Process finished with exit code 0

Am I going about this incorrectly from the Java client? I looked at similar questions, however, none of them involve JSoup and thus the structure of their POST requests is different. Note: credentials were omitted for privacy!



via Steve

Why does Query execution time is so higher for Mysql Native driver for node.js , possible alternatives?

Why does same query takes around 300 ms more than actual execution time when using Mysql native driver for Nodejs .with and without using "create pool" options.

Please refer highlighted section in below attached screenshot

Mysql workbench execution

Also for native driver execution time,Please refer below attached screenshot,

enter image description here

Codebase for node.js Mysql Native driver

var mysql = require('mysql');
var connectionpool = mysql.createPool({
    connectionLimit: 100, //important
    host: 'localhost',
    user: config.development.username,
    password: config.development.password,
    database: config.development.database,
    multipleStatements: true,
});

exports.getConnection = function(callback) {
    connectionpool.getConnection(callback);
};

 var pre_query = new Date().getTime();
    var sqlstatements = "select  * from employees where recordstate<>'raw'and  DATE(createdAt) " + "between ('1982-03-24') and ('2017-04-23')    order by employeesID desc limit 20 offset 0;" + "select COUNT(*) as count   from employees where recordstate<>'raw'and  " + "DATE(createdAt) between ('1982-03-24') and ('2017-04-23')    order by employeesID desc";
    connections.getConnection(function(err, c) {
        console.log(sqlstatements)
        c.query(sqlstatements, function(err, projects) {


            console.log(err);
            if (!err) {
                c.release();

                var red = new Object();
                red.rows = JSON.parse(JSON.stringify(projects[0]));
                red.count = JSON.parse(JSON.stringify(projects[1]))[0].count;
                var post_query = new Date().getTime();
                // calculate the duration in seconds
                var duration = (post_query - pre_query) / 1000;
                console.log(duration)
                    // console.log(red);
                res.json(red);

            }
        })
    })



via Rizwan Patel

cannot access the .id value of a resource

Trying to access $scope.mySlot.id but it is undefined.

$scope.removeMe = function(){
    UserService.me().then(function(me){
    $scope.ME = me;
    });
    var userToRemove = $scope.ME;                                       
    var shouldRemove = confirm('Remove you from this field trip?');
    if (shouldRemove) {

        var data = {
            userID: userToRemove.id,
            eventID: tripID,
        }
        console.log("data: " );
        console.log(data);
        $scope.mySlot = GreenTripFilledSlotsFactory.get(data);   
        console.log('this is $scope.mySlot: ')
        console.log($scope.mySlot);
        console.log('this is $scope.mySlot.id : ')
        console.log($scope.mySlot.id);
         console.log('this is $scope.mySlot.userID : ')

        console.log($scope.mySlot.userID)

        $scope.mySlot.$delete(function(success){
            $route.reload();
        })  

    }
}

In the console.logs $scope.mySlot is shown as a resource and it does list the values of it. But I'm confused why $scope.mySlot.id is undefined.

Here is the console:

screenshot of console



via lightcollector7

node.js app is working slower than php

I am working on a node.js application (express + mongoose) that currently has only login and registration. While developing my app I have encountered a problem that node.js is even slower than apache2 + php. The code execution time that I get after creating a new user account on node.js app: http://prntscr.com/ezmh6h and the execution time when I register a user on php website is 178.36401367188ms. Why web request on node.js app is so slow? Have you got any suggestions? Because normally node.js should be 2-3 times faster than php.

My auth.js file:

var express = require('express');
var async = require('async');
var router = express.Router();
var passport = require('passport');

var User = require('../models/user');
var Auth = require('../functions/auth');
require('../configs/passport');

router.get('/', function(req, res) {
    res.redirect('/auth/login');
});

router.get('/login', Auth.ensureNotAuthenticated, function(req, res) {
    res.render('login', {
        title: 'Login'
    });
});

router.post('/login', Auth.ensureNotAuthenticated, passport.authenticate('local', {
    successRedirect: '/',
    failureRedirect: '/auth/login',
    failureFlash: true
}), function(req, res) {
    res.redirect('/');
});

router.get('/register', Auth.ensureNotAuthenticated, function(req, res) {
    res.render('register', {
        title: 'Register'
    });
});

router.post('/register', Auth.ensureNotAuthenticated, function(req, res) {
    var username = req.body.username;
    var email = req.body.email;
    var password = req.body.password;
    var password2 = req.body.password2;

    // Validation
    req.checkBody('username', 'Username is required').notEmpty();
    req.checkBody('email', 'Email is required').notEmpty();
    req.checkBody('email', 'Email is not valid').isEmail();
    req.checkBody('password', 'Password is required').notEmpty();
    req.checkBody('password2', 'Passwords don\'t match').equals(password);

    async.waterfall([
        function(callback) {
            req.getValidationResult().then(function(result) {
                if (result.isEmpty()) {
                    var newUser = User({
                        username: username,
                        email: email,
                        password: password
                    });
                    callback(null, newUser);
                } else {
                    callback(result.array()[0].msg);
                }
            });
        },

        function(newUser, callback) {
            User.usernameExists(newUser.username, function(exists) {
                if (exists) {
                    callback('Username already exists');
                } else {
                    callback(null, newUser);
                }
            });
        },

        function(newUser, callback) {
            User.emailExists(newUser.email, function(exists) {
                if (exists) {
                    callback('Email already exists');
                } else {
                    callback(null, newUser);
                }
            });
        },

        function(newUser, callback) {
            User.createUser(newUser, function(err, user) {
                if (err) {
                    callback('An unexpected error has occurred');
                } else {
                    console.log('New user: ' + user.username);

                    req.flash('success_msg', 'You have successfully registered');
                    res.redirect('/auth/login');
                }
            });
        }
    ], function(err) {
        if (err) {
            res.locals.error_msg = err;
        }

        res.render('register', {
            title: 'Register'
        });
    });
});

router.get('/logout', function(req, res) {
    req.logout();
    req.flash('success_msg', 'You have successfully logged out');
    res.redirect('/auth/login');
});

module.exports = router;

User model:

var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');

var Schema = mongoose.Schema({
    username: {type: String},
    email: {type: String},
    password: {type: String}
});
var User = module.exports = mongoose.model('users', Schema);

module.exports.createUser = function(newUser, callback) {
    var salt = bcrypt.genSaltSync(10);
    var hash = bcrypt.hashSync(newUser.password, salt);
    newUser.password = hash;
    newUser.save(callback);
}

module.exports.usernameExists = function(username, callback) {
    User.findOne({username: username}, function(err, result) {
        if (err) {
            callback(true);
        } else if (result) {
            callback(true);
        } else {
            callback(false);
        }
    });
}

module.exports.emailExists = function(email, callback) {
    User.findOne({email: email}, function(err, result) {
        if (err) {
            callback(true);
        } else if (result) {
            callback(true);
        } else {
            callback(false);
        }
    });
}

module.exports.getUserByUsername = function(username, callback) {
    User.findOne({username: username}, callback);
}

module.exports.getUserById = function(id, callback) {
    User.findById(id, callback);
}

module.exports.comparePassword = function(password, hash, callback) {
    bcrypt.compare(password, hash, function(err, res) {
        if (err) {
            callback(null, false);
        }
        callback(null, res);
    });
}



via WaScript3r

Change global variables programmatically using Heroku?

I currently have an application built with Express.js that runs via Heroku. I need to define a global variable that I can decrement each time a specific function is called, but I'm not sure how to do that programatically. I have a file of constants called consts.js and was trying to just set the variable (REMAINING) as follows: CONST.REMAINING -= 1 whenever the function is called, but unfortunately that doesn't work. What is a better way to go about this?



via user3802348

Asynchronous method in while loop with Graph API paged

I'm using facebook node sdk for node.js to get information from facebook user like feed and friends and all are working fine, but I'm having issue when the returned data is paged - I need to built something in recursive mode. Let me explain:

FB.api('/me/feed?limit=5000', {
    access_token: token
}, function(response) {
  // response is an object that could have as response.paging.next attribute
}); 

Limit doesn't working here, because it returns max 245 and returns paging object indicate to the next page.

Because the next call depends of the result of the before async call, I tried to do something like this:

// first call before
var hasNext = response.paging.next ? true : false;
while (hasNext){
    FB.api('/me/feed', {
        access_token: token
    }, function(response_paged) {
       response.data.concat(response_paged.data);
       // If do not have a next page to break the loop
       if (!response_paged.paging.next) hasNext = false;
    });
} 

The way as the next token Was obtained is not important for now

The point is I'm trying to do async calls in recursive mode, but is not working, this way I'm getting infinite loop.



via Lucas Costa

How to Handle ES7 - Unhandled promise rejection in async object method in Node.js expressjs?

Im using the async function inside the object to send a response in express.js

Controller Code :

module.exports = {

    async signUpEmail(req, res) {

        /**
         * @description Parameters from body
         * @param {string} firstName - First Name
         * @inner
         */  

        const firstName = req.body.firstName;

        res.send({ success: name });
        throw new Error(); // purposely Done
    }
}

Question:

Since the signUpEmail method is async in my case and it will get rejected with whatever my async method throw's here it's comes Error.(purposely put there)

so getting this logged in the console.

(node:13537) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error
(node:13537) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

So i'm supposed to handle it from the routes from where i'm calling it.

Router Code

    const routes = require('express').Router();
const SignUpController = require('../controllers/signUpController')

// /signup
routes.post('/', SignUpController.signUpEmail);

module.exports = routes;

some what like this SignUpController.signUpEmail().then(…); But since i'm not calling function in the routes i'm just passing. How this can be done effectively ?

PS:Please Don't suggest too complicated solutions. I'm beginner with JS and is learning through.

I Didn't use chainable route handlers because i want to create modular, mountable route handler.

Official Doc Example - http://expressjs.com/en/guide/routing.html#express.Router



via Ankur Anand

What are the correct steps to publish npm package?

TL;DR: I need a guide to synchronous publishing new versions of a project as a release on GitHub and an npm package.


Suppose I have a project on GitHub called "webcats". I've just made an initial major release with a tag v1.0.0 and successfully npm published it as webcats@1.0.0. And then I've decided to add new features to the project.
I need the version v1.1.0 both as a GitHub Release and as an NPM package.

How do I achieve that?
I understand the possible silliness of the question, but I really stuck here.



via Dmitry Parzhitsky

"Cannot read property 'username' of undefined" - it IS defined?

I have the following index.pug file on my server that I am trying to render:

block content
    h1.
        User List
          ul
            each user, i in userlist
              li
                a(href="mailto:#{user.username}")= user.username

And my node.js app's code:

app.get('/sign-up', function(req, res) {
var db = req.db
var collection = db.get('_User')
collection.find({},{},function(e,docs){
res.render('index', {"userlist":docs})})
})

I get the following error upon trying to open 'sign-up': "Cannot read property 'username' of undefined"

Why might I be getting this error? I do have the collection called '_User' and it has 'username' key in it.



via kupak12

Include static data files in an NPM package, use them in a portable way

I want to publish an NPM package that contains a large-ish amount of static data files. There could be 1000 files, containing 1 KB of data each, yielding 1 MB or so of data. It is important that that the environment only load files as they are required by the code (which is determined at runtime).

I want the package to be usable from both server and client, and using any CommonJS implementation.

How can I do this in a user-friendly way?

Although less important, is there a way to structure the code so that a module system is not required? (e.g. so the code and data can be used through HTML tags).

While specific environments have ways to require static data files, those are different and environment-dependent. Different environments also have different ways of accessing the files (in a web browser, you'd send a GET request, while in a server environment you'd read the file from the file system).



via GregRos

How to check object null and then property null and then assign value if they are null?

I am trying to check if a variable is null inside an object in single line

 let data = {                        
   friends: userData.social.friends?0: userData.social.friends,
}

in the above line how to check if the userData is null and social is null and then friend is null in a single line? i need to set 0 if friends is not there.

this is in my javascript node js app



via face turn

Can't retrieve data from associates in Sequelize

I'm pretty new to NodeJS in general and even new to Sequelize. As an exercise, I'm trying to convert a .NET Core application I have while maintaining the SQL schema I have. To do this, I started with the Sequelize / Express tutorial they had on their website. From there, I read through the documentation and created several models to work with that match my .NET app.

Building

module.exports = function (sequelize, DataTypes) {

var Building = sequelize.define('Building', {
    BuildingId: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    Name: {
        type: DataTypes.STRING,
        allowNull: false
    }
}, {
    classMethods: {
        associate: function (models) {
            Building.belongsTo(models.Campus, {
                foreignKey: 'CampusId'
            });

            ....
        },
        getByCampus: function (models, campusId) {
            this.findAll({
                include: [{
                    model: models.Campus,
                    where: {
                        CampusId: campusId
                    }
                }]
            }).catch(function (err) {
                return Promise.reject(err); // This doesn't seem to get passed to express?
            });

            ....

Campus

module.exports = function (sequelize, DataTypes) {
'use strict';

var Campus = sequelize.define('Campus', {
    CampusId: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    Enabled: {
        type: DataTypes.BOOLEAN,
        defaultValue: true,
        allowNull: false
    },
    Name: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: true
    }
}, {
    classMethods: {
        associate: function (models) {
            Campus.hasMany(models.Building, {
                as: 'Buildings',
                onDelete: 'CASCADE',
                foreignKey: 'CampusId'
            });

            ...

Route

router.get('/:id/building', function (req, res, next) {
    var campusId = parseInt(req.params.id);
    models.Building.getByCampus(models, campusId).then(function (buildings) {
        res.send(buildings);
    }).catch(function (err) {
        res.send(err);
    });
});

What I'd like is:

  • To be able to access the Campus from an instance of Building
  • Be able to access Buildings from an instance of Campus
  • Be able to get a single Building from my Building model by CampusId

What I'm getting is:

Executing (default): SELECT Building.BuildingId, Building.Name, Building.createdAt, Building.updatedAt, Building.CampusId, Campus.CampusId AS Campus.CampusId, Campus.Enabled AS Campus.Enabled, Campus.Name AS Campus.Name, Campus.createdAt AS Campus.createdAt, Campus.updatedAt AS Campus.updatedAt FROM Buildings AS Building INNER JOIN Campuses AS Campus ON Building.CampusId = Campus.CampusId AND Campus.CampusId = 1; GET /api/v1/campus/1/building 500 10.639 ms - 1968

It's completely ignoring my catch in Building.getByCampus, though if I set a break point, I can confirm I'm getting to the function. What dumb thing am I missing? I've spend several hours trying different things and re-reading their docs and feel like I'm hitting a wall.



via jackmusick

Limit of socket connection in Node JS

I use socket server with my love Node JS.

It is very perfect.

But i have a important question.

How many connection i can accept in node js?

Is there any limit for get connection?



via Omid Aghakhani

Using knex SELECT query results for another SELECT query

I am trying to run a PostgreSQL query with Knex and then use the results to run another query.

exports.buildBuoyFeaturesJSON = function (conditionA, conditionB) {
var query = null;

var selectedFields = knex.select
(
    knex.raw('t_record.id AS id'),
    ...
    knex.raw('t_record.latitude AS latitude'),
    knex.raw('t_record.longitude AS longitude')
)
    .from('t_record')
    .then(function (response) {
        var geometry_array = [];
        var rows = response.rows;
        var keys = [];

        for (var key = 0; key <= rows.length - 1; key++) {
            var geometry =
                {
                    "id" : rows[key].id,
                    "type" : "Feature",
                    "geometry" : rows[key].geometry,
                    "properties" : {
                        ...
                        "sensors" : []
                    }
                };
            keys.push(rows[key].id);
            geometry_array.push(geometry);
        }
        getMeasurementsAndSensors(keys, geometry_array);
    });
};

The latter function uses some of the results from the previous function. Due to asynchronous nature of Knex, I need to call the second function from inside the first function's .then() statement:

function getMeasurementsAndSensors (keys, geometry_array) {
        var query = knex
            .select
            (
                't_record_id',
                'i_sensor_id',
                'description',
                'i_measurement_id',
                't_sensor_name',
                't_measurement_name',
                'value',
                'units'
            )
            .from('i_record')
            ...
            .whereRaw('i_record.t_record_id IN (' + keys + ')')
            .orderByRaw('t_record_id, i_sensor_id ASC')
            .then(function (response) {

        var rows = response.rows;
        var t_record_id = 0;
        var i_sensor_id = 0;
        var record_counter = -1;
        var sensor_counter = -1;

        for (var records = 0; records <= rows.length -1; records++) {
            if (t_record_id !== rows[records].t_record_id) {
                t_record_id = rows[records].t_record_id;
                record_counter++;
                sensor_counter = -1;
            }

            if (i_sensor_id !== rows[records].i_sensor_id) {
                i_sensor_id = rows[records].i_sensor_id;

                geometry_array[record_counter].properties.sensors[++sensor_counter] =
                {
                    'i_sensor_id' : rows[records].i_sensor_id,
                    't_sensor_name' : rows[records].t_sensor_name,
                    'description' : rows[records].description,
                    'measurements' : []
                };
            }

            geometry_array[record_counter].properties.sensors[sensor_counter].measurements.push
            ({
                    'i_measurement_id': rows[records].i_measurement_id,
                    'measurement_name': rows[records].t_measurement_name,
                    'value': rows[records].value,
                    'units': rows[records].units
            });
        }
        //wrapping features with metadata.
        var feature_collection = GEOGRAPHY_METADATA;
        feature_collection.features = geometry_array;

        JSONToFile(feature_collection, 'buoy_features');
    });

}

Currently I save end result to a JSON file because I couldn't get Promises to work. JSON is later used to power a small OpenLayers application, hence the JSON-ification after getting results.

I am quite sure that getting the data from a database, saving it to file, then accessing it from another process and using it for OpenLayers is a very redundant way to do it, but so far, it is the only one that works. I know there are a lot of ways to make these functions work better, but I am new to promises and don't know how to work with them outside of most basic functions. Any suggestions how to make this code better are welcome.



via jjustas

How to find an alchemy API key?

I was wondering where can I find my alchemy API key on Bluemix? I looked at the following question on SO (Where to get the Alchemyapi API key?) however, my bluemix looks nothing like that.

I do not have an apikey field, only username and password along with a url. IBM's documentations are approaching the usefulness of Java Docs (I.E, loads of info very little as far as demos go)

Below is how my creds look like:

{
  "url": "so_url",
  "username": "3e49e046-....",
  "password": "XXXX"
}

I downloaded the npm module using the following instructions (https://www.npmjs.com/package/watson-developer-cloud#alchemylanguage) it mentions that username and password are the api key, so do they just get concatenated together? Is there anything that I missing from my Bluemix by chance?

The way i have my api key now, i.e where it is just username and password merged together returns an invalid api key error.



via SomeStudent

How to boot up react and node api server on same port?

I built a simple express api server on port 8080. In another port(3000) i am building the client side with react which fetch data from my express api endpoint. For this i will have to run both of these applications on separate port. How can i run both of these in same port eg. 8080? I am pretty new at this. help would be really appreciated.



via ShocKwav3_

Error in app.js file that I can't crack

I'm getting an unexpected token error when I try to run the following app.js code via node. It says the problem is on or around line 15. Am I missing a bracket or something? It's probably something simple, but I just don't see it.

enter image description here



via Koberlander

Implementing public and followers only news feed

I want to implement a news feed where users can post both private ( shared ) and public activities. The difference between the two is public activities are shown in all the user's news feed and private activities are shown to all of my followers news feed.

I have been reading some resources about implementing news feed and I have come across this open source project.

Quoting from the documentation

Next up we want to start publishing this activity on several feeds. First of all we want to insert it into your personal feed, and then into your followers' feeds

Now this works well for private activities, I post the activity to author's own feed as well as all of my followers feed. But the issue is when the activity is public. In this case I have to post it to user's own feed as well as all other users in the system so that this activity is shown in their feed. Suppose there are 1 million users in the system than this will require posting to 1 million feeds (possibly 1 million DB records). I believe this is not correct.

I thought of separating out public activities in other collection and these activities are visible to all. This issue with this solution is suppose I want to retrieve a user's feed than how do I combine data from user's followers feed with public feed.

Consider this example.

User A has 10 followers and they posted 10 activities in total. So User A's feed has 10 activities from his followers. Now there is User B which user A does not follow. User B also posted 2 public activities. Now the user A's feed should have 12 activities (10 from followers + 2 from user B public activities) so I do I combine data from these two collection and implement sorting, filtering etc on the combined result set.

Additional Info: platform: node.js DB: rethinkdb



via Ritesh

Downloading a File from HapiJs Server

I need a little help I want to generate a pdf report.

I'm using PDFKit Node Module

const PDFDocument = require("pdfkit");

function generatePDF(request, reply) {
  let doc = new PDFDocument();
   let path = __dirname + "/payments/" + "filename" + ".pdf";



  doc.text = "Hello World!";
  doc.text = "Hello Me!";
  doc.end();  
  return reply(doc)
       .header('Content-disposition', 'attachment; filename=' + 'payments.pdf')  

}

On the client-side, I have tried so many things:

1.

button.addEventListener("click", function (event) {
        axios.get('/payment-pdf')
            .then(function (response) {
                console.log(response);

            })
            .catch(function (error) {
                console.log(error);
            });

    }, false)

2.

<a href="/payment-pdf" download>Export</a>

How do I download the PDF file? It seems as a simpe task, but I'm not able to get it done.

Thank you.



via Clinton Yeboah

Express subdomain

I have a website with Express that is on server alex.mysite.org. I want to add a subdomain, for example, test.alex.mysite.org. So I have this code:

var express = require('express');
var app = express();

var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer();

var wildcardSubdomains = require('wildcard-subdomains');

app.use(wildcardSubdomains({
        namespace: '_sub',
        whitelist: ['www', 'main'],
}));

app.all('/_sub/teste/*', function(req, res) {
        proxy.web(req, res, {target: 'http://127.0.0.1:3001'});
});

app.all('/*', function(req, res) {
        proxy.web(req, res, {target: 'http://127.0.0.1:3000'});
});

app.listen(80);

Everything was working, but I added the 'wildcard-subdomains' module and now my website is giving a 404.
Can someone help me?



via alexandre1985

Google API oauth for devices returns { error: 'invalid_request' }

I'm attempting to authorize the google calender API for an Amazon Alexa skill, using the instructions listed here. I believe the process is a little different since the app is on a device with no screen and therefore has to be processed differently.

The POST request that I am making only returns { error: 'invalid_request' }, and I cannot figure out why. Here is my POST request (node)

var request = require('request');
request.post(
    'https://accounts.google.com/o/oauth2/device/code',
    { json: { 
        client_id: '51362933288-lfin0rvo7pu2frlcpc3oc5eqjofg0ns8.apps.googleusercontent.com', 
        scope: 'https://www.googleapis.com/auth/calendar'
    } },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body);
        } else {
            console.log("Error: "+error);
        }
    }
);

I've seen a bunch of other people who have issues and their requests include the client secret or redirect URI etc etc, but I haven't included these simply because I've just been trying to follow the instructions listed on the website i linked. Any insight as to what I'm doing wrong here? Thanks!



via mcheah