Saturday, 22 April 2017

Error: Can't set headers after they are sent

In my node app, I have routes called index and home. While trying to redirect from index to home route it throws the following error:

Error: Can't set headers after they are sent

Here is the code:

app.get('/index', function (req, res) {
  res.redirect('/home');
})
app.get('/home', function (req, res) {
  res.send('Welcome Home !!');
})



via iJade

How do I implement a premade node.js module into my android application?

I am trying to write an alternate android app to manage the pavlok bluetooth device. The company that manufactures the device have publicly released an api to encourage development for it. It can be found here: https://github.com/Behavioral-Technology-Group/Pavlok_Node_Module The API is a node requiring the installation with node.js to run. I have no idea how to do this within the bounds of my android app, and after hours of research I still have no idea. I'm relatively new to android development so please be specific with your answer, thank you.



via Defunked-Melon

Unable to exchange public_token for an access_token with Plaid API

I'm using Plaid Link on the client and Node on the server. The Plaid item is successfully created with Plaid Link and returns a public_token. I then hit an endpoint on the server that uses the Plaid client to call plaidClient.exchangePublicToken(public_token).

Every single time I try to exchange the public_token, I receive a error without any details that simply states Could not exchange public_token!.

I have deducted that the most likely reason for this error is a problem with my plaidClient. All other functionality seems to be working until I try to use the plaidClient to call exchangePublicToken.

I have been trying to get past this issue for days and would really appreciate any insight into what might be preventing me from exchanging my public_tokens.

Below is the server-side code I'm using to perform the token exchange.

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var plaid = require('plaid');

// fake keys for this example
var PLAID_CLIENT_ID = '123123123123';
var PLAID_SECRET = '123123123123123';
var PLAID_PUBLIC_KEY = '123123123123123';
var PLAID_ENV = 'development';

// Initialize the Plaid plaidClient
var plaidClient = new plaid.Client(
    PLAID_CLIENT_ID,
    PLAID_SECRET,
    PLAID_PUBLIC_KEY,
    plaid.environments[PLAID_ENV]
);

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));

router.post('/authenticate_item', function(req, res, next) {
  var accountPublicToken = req.body.public_token;
  plaidClient.exchangePublicToken(accountPublicToken, function(error, tokenResponse) {
    if (error != null) {
        var msg = 'Could not exchange public_token!';
        console.log(msg + '\n' + error);
        return res.json({error: msg});
    }

    var accessToken = tokenResponse.access_token;
    console.log('Access Token: ' + accessToken);

  });
});



via Trey Granderson

Difference in file size between Nginx and Express server when serving static bundled Js and css

I am trying to optimize serving my static bundles generated from my React Webpack app. In this process, I noticed that for same files, when serving the content through an Express server, the file sizes were comparatively lower than when served through nginx.

Here is my express code to serve the bundle:

app.use(express.static(project.paths.dist()));

Here is my nginx config:

server {
listen 80;

root /home/test/dist/;
index index.html index.htm app.js;

server_name www.ranodom.com;

location / {
    try_files $uri /index.html;
}

error_log /var/log/nginx/test/website-error_log error;
access_log /var/log/nginx/test/website-access_log;
}

When served through express:

Express served files

When served through nginx: Nginx served files

As visible from above screenshots, the file sizes differ drastically. The actual file sizes as present in the folder is equal to the one being served from Nginx server.

My question is, what can be the reason for this difference? Does express static optimizes/compresses the served files or is there a catch? If there is so much difference, would it be better to serve these files via express server and routing to index page via nginx?

PS. The above files are already uglified and minified using webpack.



via codeslayer1

How to read property of 'id' using express-session?

This is my mongoose schema for work:

var mongoose = require('mongoose');

var WorkSchema = mongoose.Schema({
Title:{
    type:String,
    required:true, 
    unique:true
},
   VideoURL:String,
   Image: { data: Buffer, contentType: String },
   Price:Number,
   Username:String,
   Company_id:[{type:mongoose.Schema.Types.ObjectId, ref:'Company'}]

});

var Work = module.exports = mongoose.model("Work", WorkSchema);

And this is the my work controller:

    let Work = require('../Models/Work');
    let Company = require('../Models/Company');
    let WorkController = {
     createWork:function(req, res){

       let   trial = new  Work();
       console.log( req.session.Username+ " session");
       trial.Username= req.session.Username;
       trial.VideoURl= req.body.VideoURl;
       trial.Price=req.body.Price;
       trial.Title= req.body.Title;
       User=req.session.Username;

Company.findOne( {Username:User},function(err, company){
            trial.Company_id=company._id;


            trial.save(function(err, Work){
            if(err){
               res.send(err.message);
               console.log(err);
           }


          });
       });
    }
 }


 module.exports = WorkController;

And this is my schema for Company: let Company = require('../Models/Company');

let CompanyController = {



login:function(req,res){
var Username = req.body.Username;
var  Password =req.body.Password;

 Company.findOne({Username:Username,Password:Password},function(err,Company)
    {
      if(!Company){

              return console.log('you are not athorized ');
 res.status(500).send(errorMsg);

                 ;}
            else{
                 res.json(Company);
                req.session.Username = Company.Username;
                console.log("username session: " + req.session.Username);

              }
        })
  }
,

      createCompany:function(req, res){
         let company = new  Company(req.body);

   company.save(function(err, company){
            if(err){
                res.send(err.message)
               console.log(err);
            }
             else{
  req.session.Username= req.body.Username;

                console.log(company);

            }
         })
    }
}

  module.exports = CompanyController;

When the the company user logs in and tries to create work, this error appears in the console "TypeError: Cannot read property 'id' of null"



via user7632716

Using AWS CodeBuild run jasmine tests before deployment

Folks, Have been trying to figure out the correct way to fire of a CodeBuild project which either produces the artifact after compiling and running jasmine tests, or fails and stops the CodePipeline from proceeding with deployment.

If my buildspec.yml looks like:

version: 0.1

phases:
  install:
    commands:
      - echo Installing... Running npm install
      - npm install
  pre_build:
    commands:
      - echo pre_build...
  build:
    commands:
      - echo Testing... Running npm test
      - npm test
  post_build:
    commands:
      - echo Build completed on `date`
artifacts:
  files:
    - '**/*'

How should I fail out of the npm test phase? If any of the jasmine tests fail during npm test, will the artifact still be produced?

Thanks!



via Cmag

Building a website for users to chat with video, audio and text with nodeJS

I am trying to build a website kind of like https://appear.in/ I have built already a text chat like you can see here http://videochat-pap.herokuapp.com/

I am using socket.io over nodeJS, and I am trying to implement a way to have a video chat type. My inicial goal was to have a many-to-many skype like conference, but now i only need one-to-one kind of call, but without the call itself, just enter the website, enter your username and there you have it, a call to the next persons that enters the room.

I tried to figure out how I can make that but everytime I find something on google it tells me that either I need to use a call kind of system or I can't use socket.io

Some of the library I have heard off are

  • EasyRTC
  • SimpleWebRTC
  • PeerJS

I want to know if any of this is an option, and if it's really necessary to loose socket.io, and just stick with one of those options.



via Gonçalo Correia