Saturday, 20 May 2017

node mongoose : how to set unique index only within an embedded document

Using the following Group Schema , will the role.name be unique IN the group only ? I would like to be able to store the same role name into another group button in the same group ...

/**
 * Role Schema
 */
const Role = new mongoose.Schema({
  name: { type: String, required: true, unique: true },
  description: { type: String, required: false }
});

/**
 * Group Schema
 */
const GroupSchema = new mongoose.Schema({
  name: { type: String, index: { unique: true, required: true, dropDups: true } },
  description: { type: String, required: false },
  roles: [Role],
  createdAt: {
    type: Date,
    default: Date.now
  }
});



via erwin

Promise doesn't wait before passing to next function

I am trying to insert all transactions into a database after I've parsed them. I have a function called load.newload(transactionlist); which is passed after baby parse finishes parsing.

I've tested my code, and it loads all the files if the file list is short, but once it gets long (around 10 files or more), it calls the load.newload(transactionlist) function even before it finished parsing.

I was thinking maybe I should have another promise for the baby.parse function, but it doesn't seem to work.

Results look like this:

parse file1, parse file2, parse file3, SQL connected, Insert data successful, parse file4, parse file5

How can I fix this?

This is my code:

var baby = require('babyparse');
var read = require('read-file');
var Promise = require('promise');
var load = require('../sql/insert');



var transactionlist = [];

var incomingfile = function(file){

        //async load file and then parse after loading
        var promise = new Promise(function (resolve, reject) {
              read( file, 'utf8', function (err, res){
              if (err) 
                {
                    reject(err);
                    console.log('Oops, an error occured while parsing the data: %s', err);
                }
              else {

                    resolve(res);
                    console.log(file);
               }
            });
        }).then(function (results){


                var promise = new Promise(function (resolve, reject) {
                baby.parse(results , {

                    dynamicTyping: true,
                    delimiter: "|",
                    complete: function (results, error) {


                        if(error)
                        {

                            console.log('Something went wrong');
                            reject(error);

                        }
                        else {

                                    for(i = 1; i < results.data.length - 1; i++)
                                {

                                    var transaction  = {

                                        column1 : results.data[i][14].substring(0, 6),
                                        column2: results.data[i][2].split(' ').join(''),
                                        column3: results.data[i][14].split(' ').join(''),
                                        column4: results.data[i][8],
                                        column5: results.data[i][9]

                                    }


                                    transactionlist.push(transaction);


                                }//end for loop


                                resolve(results);

                                }

                        //console.log("Finished:", JSON.stringify(results.data));

                    }//end baby parse complete:function


                    });//end baby parse function


                }).then(function (results){

                    load.newload(transactionlist);

            });//end inner .then function


        });//end .then function


}//end incoming file function


exports.incomingfile = incomingfile;



via Joe

Bot framework to work with LUIS intent & match intent & pro-active dialog

I've built a bot using LUIS framework which works fine. while working on it came through few points as mentioned below

  1. After connecting with LUIS intent; bot is unable to check with regex intents like

    for ex dialog.matches('^helpdesk/i',function()) which i'm trying to setup

var dialog = new builder.IntentDialog({ recognizers: [recognizer] });

  1. How to proactively send greetings message to user before inititates conversation like i would send prompt of choices to user which user can select. If nothing is fitting to that requirement i want LUIS to work and understand on that
  2. How to know the logged in user context in Skype for Business channel
  3. cards are not working in skype for business


via Shujaath Khan

Multiple SQL WHERE query in node.JS using Array

I need simply code in my SQL query. Using SET is possible to do with an Array, but when i do with WHERE query, there's any error. Is it possible using WHERE in arary? I've been read documentation but i can't found it for MULTIPLES WHERE query

Example :

var values = {
  date : "2017-03-03 12:11:09",
  ticket_id : "12212",
  status : "Done"
}

var condition = {
  id : 21,
  status : "Pending"
}

pool.query("UPDATE queue SET ? WHERE ??", [values, condition], function(err, results){
   if(err){
      console.log(err)
      return
    }
    console.log(results)
})

And i found some error

{ Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' `status` = 'Pending'' at line 1

Thank you,



via Ade Firman Fauzi

Error: Cannot find module 'gulp-uglify/minifier'

Environment

Ubuntu 17.04

Steps

Installed Node via official instructions:

curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs

Installed gulp via official instructions:

npm install --global gulp-cli

Which caused permission errors, so followed official instructions:

# Make a directory for global installations:
mkdir ~/.npm-global

# Configure npm to use the new directory path:
npm config set prefix '~/.npm-global'

# Open or create a ~/.profile file and add this line:
export PATH=~/.npm-global/bin:$PATH

# Back on the command line, update your system variables:
source ~/.profile

Created a package.json file in my project folder with this content:

{
  "devDependencies": {
  },
  "dependencies": {}
}

Ran the following in my project folder:

npm install gulp --save-dev
npm install gulp-clean-css --save-dev
npm install gulp-concat --save-dev
npm install gulp-rename --save-dev
npm install gulp-sass --save-dev
npm install gulp-uglify --save-dev
npm install pump --save-dev
npm install uglify-js-harmony --save-dev

Which then populated the package.json file so it looked like:

{
  "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-clean-css": "^3.3.1",
    "gulp-concat": "^2.6.1",
    "gulp-rename": "^1.2.2",
    "gulp-sass": "^3.1.0",
    "gulp-uglify": "^3.0.0",
    "pump": "^1.0.2",
    "uglify-js-harmony": "^2.7.7"
  },
  "dependencies": {}
}

The relevant task in gulpfile.js looks like this:

// BEGIN get gulp plugins
var gulp = require('gulp');
var pump = require('pump');
var rename = require('gulp-rename');
var uglifyjs = require('uglify-js-harmony'); 
var minifier = require('gulp-uglify/minifier');
var cleanCSS = require('gulp-clean-css');
var concat = require('gulp-concat');
// END get gulp plugins

gulp.task('bundle_js', function () {
  // the same options as described above 
  var options = {
    preserveComments: 'license'
  };

  pump([
      gulp.src('scripts/*.js'),
      minifier(options, uglifyjs),
      concat('script_bundle.js'),
      gulp.dest('scripts_bundled')
    ]
  );
});

Running:

gulp bundle_js

Causes this error:

throw err;
    ^

Error: Cannot find module 'gulp-uglify/minifier'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/me/Desktop/myGulpProject/gulpfile.js:6:16)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)



via user1063287

Description editing using node.js and mongodb

I have a curious question that I couldn't find on the web. I don't know the name of this feature, but I want something when the user creates a post, they edit the description. I want the user to be able to make the text bigger, bold, change the color, etc. Very similar to the Stackoverflow asking questions and styling the text. What tool would I use to achieve this?

Ps. I am using Node.js and MongoDB. I have a posts model, therefore, I would like the editing description to be persistent. Meaning if the user changes the font, it would be saved to the database and shown.



via Tommy Wan

Trying to use PugJS to iterate both href attribute and link text

I'm having a hard time taking my json object and using the name and values to make a link. I've tried separate arrays as well, but I've decided it'd be easier if I set the object as {title:url} and when I use this code:

      ul
    each url, title in news
      li= title
      li= url

it returns my titles and urls like so

  • These are the arguments against net neutrality — and why they’re wrong
  • https : //techcrunch . com/2017/05/19/these-are-the-arguments-against-net-neutrality-and-why-theyre-wrong/
  • The bizarre naming trends that modern startups follow
  • https: //techcrunch . com/2017/05/20/the-bizarre-naming-trends-that-modern-startups-follow/
  • Salesforce marches steadily toward $10B run rate goal
  • https :// techcrunch . com/2017/05/19/salesforce-marches-steadily-toward-10b-run-rate-goal/
  • Uber threatened to fire engineer at center of Waymo trade secret lawsuit
  • https : //techcrunch.com/2017/05/19/uber-waymo-anthony-levandowski-termination-threat/

but when I try to make links with this code

   each url, title in news
    a(href= url) title

I get this:

titletitletitletitle

the links work, but it won't iterate the title... any tips with this issue?



via Quoc Moon Duong

SocketIO "NotRegistered" message when using io.sockets.emit

Recently an application I built using SocketIO stopping sending messages to clients out of the blue, and the message NotRegistered appears in the console whenever a message is sent. Everything else works fine, and the server has no trouble receiving requests.

One quick thing to note, the only clients having issues are ones on mobile devices (e.g iOS/Android) using the respective native mobile socket.io library.

io.sockets.emit("newMessage", {removed: removed, room: room, userID: removed, name: removed, message: messageContent});



via Jordan Osterberg

add a field and update another in array of objects

A query returns an array of objects from a collection. I want to add a field to each of the objects in that array, and update another field in every object of the array.

Products array before update:

[{ _id: 58d895b8ffc0346230a43a89,
  event: 'Junior Girls 12s',
  group: 'nonpro',
  price: 50,
  day: 'Friday' },
 { _id: 59d895b8ffc0346230a43a89,
  event: 'Junior Girls 14s',
  group: 'nonpro',
  price: 50,
  day: 'Friday', }]

My code to update the array of objects:

//add the field and changed price if late fee applies
for(var i = 0; i < products.length; i++) {
  products[i].field = registered.frifield;
  console.log(products[i].field);
  if(settings.latefeeamt > 0 && settings.frilatefee === true) { 
     products[i].price += settings.latefeeamt; 
  }
  console.log(products[i]);
  console.log(events.friday);
}

How products array SHOULD look after update:

[{ _id: 58d895b8ffc0346230a43a89,
  event: 'Junior Girls 12s',
  group: 'nonpro',
  price: 60,
  day: 'Friday',
  field: 'Main' },
 { _id: 59d895b8ffc0346230a43a89,
  event: 'Junior Girls 14s',
  group: 'nonpro',
  price: 60,
  day: 'Friday',
  field: 'Main' }]

How can I get this to work? It console.logs the correct field inside the loop, but I get the original array when it's done.



via user3561890

Express.js w/ Compass doesn't work with PM2

I have used the express-generator to generate a project with compass stylesheet engine:

express --css compass app

The app as expected when I start using npm start (or node ./bin/www, fwiw).

However, when I use pm2 to run the app, as pm2 start ./bin/www the app runs and returns an html response, but the CSS fails when the browser requests it, the process dies and pm2 restarts it. This is behind an nginx which returns a 502 Bad Gateway.

These are the pm2 logs:

0|www      | GET /home 200 320.238 ms - 914
0|www      | Error: spawn compass ENOENT
0|www      |     at exports._errnoException (util.js:1050:11)
0|www      |     at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
0|www      |     at onErrorNT (internal/child_process.js:367:16)
0|www      |     at _combinedTickCallback (internal/process/next_tick.js:80:11)
0|www      |     at process._tickDomainCallback (internal/process/next_tick.js:128:9)
PM2        | App [www] with id [0] and pid [6624], exited with code [1] via signal [SIGINT]
PM2        | Starting execution sequence in -fork mode- for app name:www id:0
PM2        | App name:www id:0 online

I can't find any info as to why this is happening, and why it's working with node, but not with pm2. Any help appreciated.



via rgthree

In nodejs, how to run SQL queries so data is ready before page is rendered?

I'm trying to run three SQL queries to get data to push to the browser. I'm new to nodejs and Express (less than a week), so I might not have some basic concepts down as to how to approach problems like these. The solution is probably something really basic.

Anyway, I'll share my code, describe what I'm trying to have happen, and then describe what actually happens with a few notes about where I think I've gone wrong.

app.get("/", function(request, response) {
    var rock_query = "SELECT COUNT(*) AS number FROM Votes WHERE shape_id = 1;
    var paper_query = "SELECT COUNT(*) AS number FROM Votes WHERE shape_id = 2;
    var scissors_query = "SELECT COUNT(*) AS number FROM Votes WHERE shape_id = 3;
    pool.query(rock_query, function(err, res) {
        if(err) {
            return console.error('error running query', err);
        }
        rock = res.rows[0].number;
        console.log("Rock votes: " + rock);
    });
    pool.query(paper_query, function(err, res) {
        if(err) {
            return console.error('error running query', err);
        }
        paper = res.rows[0].number;
        console.log("Paper votes: " + paper);
    });
    pool.query(scissors_query, function(err, res) {
        if(err) {
            return console.error('error running query', err);
        }
        scissors = res.rows[0].number;
        console.log("Scissors votes: " + scissors);
    });
    response.render("home", {
        rock: rock,
        paper: paper,
        scissors: scissors,
    });
});

I'm trying to make it so when I visit the home page, the queries run to count the number of votes for each shape, write the count for each shape to the console, push the data so when the page renders it displays the number of votes.

When I go to the home page, it displays all zeroes for each shape when the page renders. The console shows the counted votes for each shape. I've figured out that because code in nodejs runs asynchronously, the page renders before the queries have finished.

I'm not sure how I should rewrite the above code to finish the queries before rendering the page. Help?



via Forrest Wilbur

What is the best structure for a chat pub-sub? (PubSub server agnostic)

Hey guys so just so I'm using PostgreSQL with my server already so I thought I would use its PubSub capabilities with NOTIFY. I was wondering what would be the best way to publish chat messages? I thought of maybe creating one channel per user and publishing all types of messages for that user there, but I'm guessing that will eventually go over Postgres' cap for channels. Otherwise what would be the best way to structure this?



via Duxducis

How to push websocket data to angularjs scope?

I am using autobahn and socket.io to successfully open a websocket connection and log the data in the serve console.

What I'm trying to do is to make that data available as a scope variable in my controller, so i can use the ng-repeater directive to display the data on the view.

//server.js

app.get('/open', function(req, res) {
  var autobahn = require('autobahn');
  var wsuri = "wss://api.poloniex.com";
  var connection = new autobahn.Connection({
    url: wsuri,
    realm: "realm1"
  });

  connection.onopen = function(session) {

    function tickerEvent(args, kwargs) {
      console.log(args); //logging live json data

      io.on('connection', function(socket) {
        socket.on('ticker', function(msg) {
          io.emit('ticker', msg); //I need 'msg' json to be in $scope.tickers
        });
      });
    }

    session.subscribe('ticker', tickerEvent);

  }

  connection.onclose = function() {
    console.log("Websocket connection closed");
  }

  connection.open();

})

Here I am trying to take the emitting message and push it to $scope.ticker so I can display it on index.html.

//websocket.js

app.controller('websocketController', function($scope, $http) {
  open_websocket();


  function open_websocket() {
    $http.get('http://localhost:3000/open').success(function(data) {
      io.on('connection', function(socket) {
        socket.on('ticker', function(msg) {
          $scope.tickers = msg; //trying to display this data on index.html
          console.log(msg); //not logging anything
        });
      });
    });
  };
});
<h1>index.html</h1>

<body>
  <div ng-app="websocket" ng-controller="websocketController">
    <ul ng-repeat="ticker in tickers">
      <li></li>
    </ul>
  </div>
</body>

How can I accomplish this?

Not looking for jQuery solution. Thanks.



via chuckieDub

How to Apply Preferences to d3.tree node; HTML code

I have adapted a code from

https://bl.ocks.org/mbostock/4063550

to make a nice figure for the tidy arrangement of layered nodes. Assume I have a similar flare.csv file as on the webpage. The code right now assigns color based on whether a node is on an internal circle (which means the node has two links) or on an outer circle.

What I want instead is to assign a specific color (let's say blue) to the point located in the center (the parent node) whose name is flare. Also I want to assign a specific color(let's say red) to all outer-circle nodes (those have only one connection) which name is "sub".

All other nodes could be only black.

How can I implement what I want in the HTML code?

I do highly appreciate any helps.

Thanks.

HRJ



via H.RJ

Heroku push failed due to g++ not finding library

I've got an Node js web app using binding.gyp to compile a C++ standalone program. The standalone program requires libmagic.a and libz.a. Deployment failed with these errors

g++: error: /app/.apt/usr/lib/x86_64-linux-gnu/libmagic.a: No such file or directory

g++: error: /app/.apt/usr/lib/x86_64-linux-gnu/libz.a: No such file or directory

These two libraries are installed by apt buildpack at

/app/.apt/usr/lib/x86_64-linux-gnu/

with permission (shown through commands on heroku bash):

-rw------- 1 u28074 dyno 233490 Nov 20 2015 /app/.apt/usr/lib/x86_64-linux-gnu/libmagic.a

-rw------- 1 u28074 dyno 143722 Mar 3 17:52 /app/.apt/usr/lib/x86_64-linux-gnu/libz.a

I try to set full permission to those files through heroku bash but it is reset back to what it was once I exit the bash. And the push keeps failing. What should I do to make the library visible?



via gunner308

How to find a record/document using nodejs from mongodb

I dont have much experience with Javascript/nodejs. I followed this github tutorial to create a CRUD application. It is working fine. It is able to get, insert, update and delete data. However I want to add Search option in such a way, that when a use submit id and click search, the item is found in the db and shown in the same window. I am able to search the item but then displaying the content in the same window is not working. I need help. thanks



via Mian Asbat Ahmad

Serving Angular Build files from Express

I currently have a barebones angular application, where I am trying to serve the bundled files from build of my angular client app through my express server.

I am using ng-build to build the angular code and copy the contents of the dist folder into the dist folder of my server. It looks like the following

enter image description here

When I bootup the server, I can render the index.html but see the following in my console

GET /inline.bundle.js.map 404 8.875 ms - 159
GET /polyfills.bundle.js.map 404 3.486 ms - 162
GET /styles.bundle.js.map 404 2.860 ms - 159
GET /vendor.bundle.js.map 404 2.695 ms - 159
GET /main.bundle.js.map 404 2.956 ms - 157

To hook up the client to server, I have the following in app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { APP_BASE_HREF } from '@angular/common';
import { routing } from './app.routing';


import { AppComponent } from './app.component';
import {QueuedService} from "./queued.service";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [{provide: APP_BASE_HREF, useValue:'/'}, QueuedService],
  bootstrap: [AppComponent]
})
export class AppModule { }

My queued.service.ts has the following

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class QueuedService {
  host:string = "http://localhost:8080";

  constructor(private http: Http){}

}

At the moment, I am not sure if I am bridging the client and server properly.



via RRP

ReactJS & Electron - Execute Function passed by variable: string

Given a variable foo='someFunc', I'd like to be able to then call someFunc().

There is a relevant write-up about pure javascript doing exactly this here.

I can't seem to get there with React.

I'm currently doing returnFuncFromString():

export default (func: string) => {
  switch (func) {
    case 'UpAvlToast': return toasts.UpAvlToast();
    case 'UpRcvdToast': return toasts.UpRcvdToast();
    default:
      return null;
  }
};

but after a handful of maps, this will become difficult to manage. It is being used to pass constants of message and icon variables to a toastr component. It wouldn't be surprising to have hundreds of preconfigured pairs so I'm hoping for something more dynamic.

There have been similar questions in java, and pure javascript but as there are window lookup issues involved in the electron bifurcation of the main and render threads they aren't terribly helpful.



via Mark

Node JS server randomly crashing - unknown error

I'm running a Node JS server (v7.10.0 on Centos 7 64bit VPS) through Nodemon and PM2. Lately I've been get this error:

[STREAMING] Now streaming realtime logs for [0] process
0|nodemon  | events.js:163
0|nodemon  |       throw er; // Unhandled 'error' event
0|nodemon  |       ^
0|nodemon  | Error: read ECONNRESET
0|nodemon  |     at exports._errnoException (util.js:1050:11)
0|nodemon  |     at TCP.onread (net.js:582:26)
0|nodemon  | [nodemon] app crashed - waiting for file changes before starting...

It isn't referencing any of the my files and it happens randomly and not when I upload a change so I think it may not be my code. However because it mentions "TCP" it may be what I'm doing to post requests to '/socket'? These are the dependencies I'm relying on:

"dependencies": {
    "body-parser": "*",
    "ejs": "*",
    "express": "*",
    "express-session": "*",
    "express-subdomain": "*",
    "https": "*",
    "mongodb": "*",
    "uuidv4": "*"
  }

This is my app.js (main file) code:

const fs = require('fs');
const http = require('http');
const https = require('https');
const uuid = require('uuid/v4');
const path = require('path');
const bodyParser = require('body-parser');
const express = require('express');
const expressSession = require('express-session');
const app = module.exports = express();

app.set('view engine', 'ejs');
app.set('trust proxy', true);
app.use(bodyParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressSession({
    secret: uuid(),
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }
}));

/* Is there a better way to do this? Still learning Node JS */
['//',
'plans',
'contact-us',
'affiliate-program',
'terms-of-service',
'account/login',
'account/signup'
].forEach(function(value) {
    app.get('/' + value.replace('//', ''), function(req, res) {
        res.render(value.replace('//', 'index'), {res: res, session: req.session});
    });
});

/* Possible location of error? But why? */
app.post('/socket', function(req, res) {
    /* Social count variable will be used soon */
    const socialCount = req.body.socialCount;
    const socket = require('net').Socket();
    socket.connect('<removed>');
    socket.write(JSON.stringify(req.body));
    socket.end();
});

require('./mongo');
require('./rest');

const ssl = {
    key: fs.readFileSync('<removed>.key'),
    cert: fs.readFileSync('<removed>.crt'),
    ca: fs.readFileSync('<removed>.crt'),
    requestCert: true,
    rejectUnauthorized: false
};

/* Listening on 8080 because we're moving from PHP to Node JS and our designer is still working on the PHP branch */
https.createServer(ssl, app).listen(8080, function () {
    console.log('Starting server on port 8080');
});

/*

Redirect http to https

http.createServer(function(req, res) {
    res.writeHead(301, { 'Location': 'https://' + req.headers.host + req.url });
    res.end();
}).listen(80);

*/

I'm sure there are a couple things that are sub-par, if anyone has any advice let me know please. I'm still learning how to use Node JS.

The mongo and rest files I require aren't actually being ran currently, those shouldn't be the problem.

The crash seems to randomly happen, not when I upload a file or even when anyone is visiting the site. However as mentioned above, it may be linked with how I'm doing sockets due to it saying "TCP" in the error? Any ideas? Thanks for reading



via GatorFlores

How to take the Average of values in Firebase Database

In my firebase database, I have the ratings of businesses listed in my IOS app. How would I take the average of that rating whenever a new rating is added to the database or removed with Node.js? I am very new to Node so forgive me if this is a very simple question.

Here is how my firebase is organized: enter image description here



via ethanfox27

Firebase function to pick FCM token from database

I wanted to send FCM notifications to users.I installed npm and node.js on my pc and need to create JavaScript file and JSON which listen changes in database and if there is any then pick fcm token from database(Which added in database) itself and then send it to make post request to FCM server.

Javascript is not my language that's why i am getting hard time in reading official documentation. I checked few samples from github also but all picking up FCM token from auth directory.

In my scenario- User send message, Which added to Firebase Database,Now firebase function will listen changes and get FCM token,User message body,User Name from Realtime database and send it to FCM server to generate notifications.

How can i achieve this in Index.js file to get desired result. Is this possible to make custom codes for firebase?

How my realtime database look like now.enter image description here



via Ritu

nodeJS replace multiple values in one file

I want to replace N values in an existing file with placeholders.

When a post request in a ExpressJS App is fired, the placeholder values in a file have to be changed.

For example the SASS file:

$textColor: ##textColor##;
$backgroundColor: ##backgroundColor##;

And my functionality which works fine with 1 replacement:

router.post('/', function(req, res) {

    fs.readFile('main.scss', 'utf8', (err, data) => {
        if(err) {
            console.log('An error occured', err);
        }

        backgroundColorToReplace = data.replace(/##backgroundColor##/g, 
        req.body.backgroundColor);
        // This value has to be replaced as well
        textColorToReplace = data.replace(/##textColor##/g, req.body.textColor);

        fs.writeFile('main.scss', backgroundColorToReplace, (err) => {
            if(err) {
                 console.log('An error occured', err);
            }

            console.log('Colors successfully changed');
        });
    });

    res.json({
        textColor: req.body.textColor,
        backgroundColor: req.body.backgroundColor
    });
});

How can i solve this problem? Is there a way?



via derpiet

My express web application cannot authenticate with Google APIs

I am working with the Typescript code below and I have configured everything as simply as possible. On console.developer.google.com I have enabled: Google+ API, Admin SDK, and the Groups Settings API. However, when I try to make a GET request to https://www.googleapis.com/groups/v1/groups/address@domain.tld I always receive 401: Login Required.

"use strict";

// Module dependencies
import * as bodyParser from "body-parser";
import * as express from "express";
import * as google from "googleapis";
import * as GoogleStrategy from "passport-google-oauth20";
import * as logger from "morgan";
import * as passport from "passport";
import * as path from "path";
import * as session from "express-session";

namespace Groups {
    class Express {
        public app = express();

        constructor(port) {
            // Configure view engine
            this.app.set("views", path.join(__dirname, "views"));
            this.app.set("view engine", "ejs");

            // Configure morgan
            this.app.use(logger("dev"));

            // Configure bodyParser
            this.app.use(bodyParser.json());
            this.app.use(bodyParser.urlencoded({ extended: false }));

            // Configure static content delivery
            this.app.use(express.static(path.join(__dirname, "public")));

            // Configure sessions
            this.app.use(session({
                secret: "secret",
                resave: true,
                saveUninitialized: true,
            }));

            // Configure the Google strategy for use by Passport.js.
            //
            // OAuth 2-based strategies require a `verify` function which receives the
            // credential (`accessToken`) for accessing the Google API on the user's behalf,
            // along with the user's profile. The function must invoke `cb` with a user
            // object, which will be set at `req.user` in route handlers after
            // authentication.
            passport.use(new GoogleStrategy({
                clientID: "",
                clientSecret: "",
                callbackURL: "http://localhost:3000/auth/google/callback",
            }, (accessToken, refreshToken, profile, callback) => {
                // Extract the minimal profile information we need from the profile object
                // provided by Google
                callback(null, profile);
            }));

            // Initialize Passport and restore authentication state, if any, from the
            // session.
            this.app.use(passport.initialize());
            this.app.use(passport.session());

            // Configure routes
            this.app.get("/auth/google",
                // Start OAuth 2 flow using Passport.js
                passport.authenticate("google", { scope: [ "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/apps.groups.settings" ] })
            );

            this.app.get("/auth/google/callback", passport.authenticate('google', { failureRedirect: '/' }),
                function(request, response) {
                    // Finish OAuth 2 flow using Passport.js
                    response.redirect("/");
                }
            );

            this.app.get("/auth/logout", function(request, response) {
                //request.logout();
                response.redirect("/");
            });

            this.app.get("/", function(request, response) {
                response.render("index");
            })

            // Listen on provided port
            this.app.listen(port, function() {
                console.log("Listening on port", this.address().port);
            });
        }
    }

    new Express(3000);
}

I am trying to recreate this web application in an effort to teach myself Restful APIs.

Any help would be greatly appreciated.



via Brian Jenkins

SequelizeJS HasOne association error

I am relatively new to NodeJS and SequelizeJS and am facing a hasOne issue with a query I am building and I'd like to know your thoughts about this issue to find out where I gone wrong and the correct way to implement this query.

Association Here

The models where generated using sequelize-auto (pg-hstore).

Bloco Model:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('bloco_condominio', {
    id_bloco: {
      type: DataTypes.INTEGER,
      allowNull: false,
      autoIncrement: true,
      primaryKey: true
    },
    id_condominio: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'condominio',
        key: 'id_condominio'
      }
    },
    nm_bloco: {
      type: DataTypes.STRING,
      allowNull: true
    },
    ic_status: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: "A"
    }
  }, {
    tableName: 'bloco_condominio'
  });
};

Apartamento Model:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('apartamento', {
    id_apartamento: {
      type: DataTypes.INTEGER,
      allowNull: false,
      autoIncrement: true,
      primaryKey: true
    },
    id_condominio: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'condominio',
        key: 'id_condominio'
      }
    },
    nu_apto: {
      type: DataTypes.STRING,
      allowNull: true
    },
    id_bloco: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'bloco_condominio',
        key: 'id_bloco'
      }
    },
    ic_status: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: "A"
    },
    dt_incl: {
      type: DataTypes.TIME,
      allowNull: false,
      defaultValue: sequelize.fn('now')
    },
    dt_ult_alt: {
      type: DataTypes.TIME,
      allowNull: false,
      defaultValue: sequelize.fn('now')
    }
  }, {
    tableName: 'apartamento'
  });
};

Apartamento Service:

"use strict";
var model = require('../models');
var Utils = require('../utils/utils');

var service = {};
var Apartamento = model.apartamento;
var Bloco = model.bloco_condominio;
var Morador = model.morador;
var Pessoa = model.pessoa;

//Incluir relação OneToMany
Apartamento.hasMany(Morador, { as: "Moradores", foreignKey: 'id_apartamento' });
Morador.belongsTo(Apartamento, { foreignKey: 'id_apartamento' });

Morador.hasMany(Pessoa, { as: "Pessoa", foreignKey: 'id_pessoa' });
Pessoa.belongsTo(Morador, { foreignKey: 'id_pessoa' });

Bloco.hasMany(Apartamento, { as: "Bloco", foreignKey: 'id_bloco' });
Apartamento.hasMany(Bloco, { foreignKey: 'id_bloco' }); 

service.getApartamentoById = function(idApartamento) {
    return Apartamento.findById(idApartamento, {
            include: [
                { model: Morador, as: 'Moradores', include: [
                    { model: Pessoa, as: 'Pessoa'}
                ]},
                { model: Bloco, as: 'Bloco' }
            ]
        })
        .then(function(data) {
            return data;
        })
        .catch(function(err) {
            throw 'Erro ao consultar apartamento por ID: ' + err.message + ' - Request: '+JSON.stringify(idApartamento);
        });
};

I can perfectly retrieve the other hasMany associations, but still hasn't found a way to do so in the reverse way.

Do you guys have any idea of how I should approach this issue in the correct manner?

Thanks in advance for your help!

Best regards, Enrico Bergamo



via Enrico Bergamo

Unable to render static index file from express

I working on Angular application, where I am trying to server the build files from my Angular application through the dist directory in my express. To do this I copy the files generated by ng build and paste them into dist folder of express.

My dist folder looks like below

Dist Folder for Express

I am using the following code to serve the index.html file

this.app.use(express.static(__dirname + '/dist'))

But seem to be getting "Cannot GET /" error

Similarly if I do

this.app.use(express.static(__dirname + '/public'));

it serves the html in the public folder.

As far as my understanding, you can serve static from any folder in express. I am not sure if I am missing something here.



via RRP

"model.find() is not a function" error when using mongoose, node, and express

I'm currently trying to get a node.js/express tutorial working (from Express in Action), but haven't been able to access a mongoose model properly. I call the module in a var called "User" I keep getting the error that "User.find is not a function."

Here is the models/user.js file:

var
  bcrypt = require("bcrypt-nodejs"),
  mongoose = require("mongoose"),
  SALT_FACTOR = 10
;

var noop = function() {};

var userSchema = mongoose.Schema({
  displayName: String,
  bio: String
});

userSchema.pre("save", function(done) {
  var user = this;

  if (!user.isModified("password")) {
    return done();
  }

  bcrypt.genSalt(SALT_FACTOR, function(err, salt) {
    if (err) { return done(err); }
    bcrypt.hash(user.password, salt, noop, function(err, hashedPassword) {
      if (err) { return done(err); }
      user.password = hashedPassword;
      done();
    });
  });
});

userSchema.methods.checkPassword = function(guess, done) {
  bcrypt.compare(guess, this.password, function(err, isMatch) {
    done(err, isMatch);
  });
};

userSchema.methods.name = function() {
  return this.displayName || this.username;
};

var User = mongoose.model("User", userSchema);

module.exports = User;

Here is the routes.js file calling it:

var
  express  = require("express"),
  mongoose = require("mongoose"),
  flash    = require("connect-flash"),
  passport = require("passport"),
  router   = express.Router()
;

var User = ("./models/user");

router.use(function(req, res, next){
  res.locals.currentUser = req.user;
  res.locals.errors = req.flash("error");
  res.locals.infos = req.flash("info");
  next();
});

router.get("/", function(req, res, next) {
  User.find({}, function(err, users) {
    assert.equal(err, null);
    res.json(users);
  });
});

/* 
Original route, also doesn't work

router.get("/", function(req, res, next) {
  User.find()
    .sort({ createdAt: "descending" })
    .exec(function(err, users) {
      if (err) { return next(err); }
      res.render("index", { users: users });
  });
});
*/

module.exports = router;

Lastly here's the index.js file, in case it's relevant

var
  http         = require("http"),
  path         = require("path"),
  express      = require("express"),
  flash        = require("connect-flash"),
  session      = require("express-session"),
  cookieParser = require("cookie-parser"),
  logger       = require("morgan"),
  liquid       = require("shopify-liquid"),
  bodyParser   = require("body-parser"),
  mongoose     = require('mongoose')
;

var routes = require('./routes');
var app = express();

mongoose.connect('mongodb://localhost:27017/test');

app.set("port", process.env.PORT || 3000);

var engine = liquid({
    root: __dirname,  // for layouts and partials
    extname: '.liquid'
});
app.engine('liquid', engine.express()); 
app.set('views', ['./views', './views/partials', './views/layouts']); 
app.set('view engine', 'liquid');

var assetsPath = path.resolve(__dirname, "assets");
app.use("/assets", express.static(assetsPath));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
  secret: "TKRv0IJs=HYqrvagQ#&!F!%V]Ww/4KiVs$s,<<MX",
  resave: true,
  saveUninitialized: true
}));
app.use(flash());
app.use(routes);

app.use(logger("dev"));

app.use(function(request, response) {
  response.status(404).render("404");
});

http.createServer(app).listen(3000, function(){
  console.log('App skeleton started on port 3000.');
});

I've tried the solutions suggested from all similar questions but had no luck.



via Max Antonucci

Running a function after async operation is complete

I'm banging my head against the wall to figure out how to push data that is being written on file asynchronously into an array. Writing the data synchronously (and checking if the item is the last on the list) takes too much time so I decided to make it run async. After doing some research, it seems that I could use a callback

I would prefer not to use an external library for doing this, since I'm pretty sure either a callback or a Promise should do the trick. Thanks!

//Iterate through list and make HTTP request to get data
dataDocument.map(function(item, index) {

    request(item, function(err, res, html) {
        if (err) throw err;
        renderData(html, item);
    });

});

//Renders data 
function renderData(html, item) {
    ...some calculations here.

    writeData(output, id, function() {
        pushed(output);
    });
};

//Writes the data on file
function writeData(output, id) {
    fs.appendFile('./output.json', output);

//SHOULD I USE A CALLBACK HERE TO PUSH INTO AN ARRAY ONCE IT'S COMPLETE?

};

//NEED HELP HERE: Pushed the data into an array and eliminates last comma.
function pushed(data) {
   var arr = [];
   arr.push(data);
}



via agomez

Google Cloud Platform Datastore user authorization in Node.js

In Google Cloud App Engine I deployed a web app using node.js, To authenticate users I used OAuth 2.0.

How can I allow users to access only their data in Datastore without using filters?



via Zvi Karp

Populate and Virtuals with mongoose returning imcomplete data

I need some help with populate and virtuals with mongoose.

When I get a list of the "cidade" using

router.get('/',function(req,res,next){ ....

I´d like to populate the result with some additional info from "estado" as "_id " and "nome".

Buit, when I print the results in the console, I have only results from "cidade" and no data informations from "estado".

What am I doing wrong?

//collections data sample

//cidades

    "_id":213123......
    "uf":"AL"
    "cidade":"ARARAS"
......

//estados

    "_id":2aaa3123......
    "uf":"AL"
    "nome":"AZALU"
.....

//router to cidades

'use strict';
const express = require('express');
const router = express.Router();
//const querystring = require('querystring');
const Cidade = require('../models/cidade'); 
const callback=function(err,data,res){
     console.log(data);//??? only data from "cidade", no "estado" info
     if (err) return res.status(500).json(err);
     return res.status(200).send(data);
};

router.get('/',function(req,res,next){
    const query=new RegExp(req.query.where,'i');
    Cidade.find({ cidade: query })
    .populate('id_estado')
    .exec( (err,data) => {
       callback(err,data,res)
    })
});

//model estados

estadosSchema = new mongoose.Schema({
  uf: {type: String, unique:true},
  nome: {type: String, unique:true}
});
module.exports = mongoose.model('Estado', estadosSchema,'estados' );

//model cidades

cidadesSchema = new mongoose.Schema({
  uf: {type: String, unique:true},
  cidade: {type: String, unique:true}
},{ toJSON: { virtuals: true } });

cidadesSchema.virtual('id_estado', {
  ref: 'Estado', // The model to use
  localField: 'uf', // Find Estado where `localField`
  foreignField: 'uf', // is equal to `foreignField`
  justOne: false
});


module.exports = mongoose.model('Cidade', cidadesSchema,'cidades' );



via Luiz Alves

Nodejs Koa2: TyperError: ctx.render is not a function

I am pretty new to Node and Koa2, so please bear with me.

I am getting this error:

TypeError: ctx.render is not a function

This is the line where the error gets triggered:

class HtmlRouter {
    static async home(ctx) {
        await ctx.render('index.ejs', {});
    }
}

I am using ejs as the templating engine.

What am I doind wrong or missing?



via Xar

Reverse proxy websockets (socket.io) server using NGINX - 502 (Bad Gateway)

My Setup

On Ubuntu 16.04.2 LTS (Amazon AWS EC2):

My app server.js

const express = require('express');
const app = express();
const fs = require('fs');
const https = require('https');
const io = require('socket.io');
const request = require('request');

const port = 3000;

const options = {
    key: fs.readFileSync('./config/ssl/server.key'),
    cert: fs.readFileSync('./config/ssl/server.crt')
};

const httpsServer = https.createServer(options, app)
const ioServer = io(httpsServer, {
    path: '/my-app/socket.io'
});

app.set('view engine', 'ejs');
httpsServer.listen(port, function() {
    console.log("Listening on port " + port);
});

app.get('/index', function(req, res) {
    res.render(path.join(__dirname + '/views/index'));
});

app.get('/my-app/:var', function(req, res) {
   ... some code ...
}

/*
 * SocketIO server with namespace 
 */ 
var nsp = ioServer.of('my-app-sockets');

nsp.on('connection', function(socket) {
   ... more code ...
}

For the WebSocket connections, loading this Javascript in my HTML page

var mlSocket = io.connect("https://my.domain.com/my-app-sockets", {
    path: '/my-app/socket.io'
});

Where my-app-sockets is the namespace set in server.js

My NGINX configuration

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include            mime.types;
    default_type       application/octet-stream;
    sendfile           on;
    keepalive_timeout  65;

    upstream app_server {
        server 127.0.0.1:3000;
    }

    upstream another_server {
        server www.anotherdomain.com;
    }

    # HTTPS server
    #
    server {
        listen       443 ssl;
        server_name  localhost;

        ssl_certificate      /etc/ssl/self-signed-certs/server.crt;
        ssl_certificate_key  /etc/ssl/self-signed-certs/server.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        #
        # my-app
        #
        location ~ ^/(my-app|index) {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-NginX-Proxy true;
            proxy_pass https://app_server;
            proxy_redirect off;

            # WebSocket support
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }

        location ~ ^/(images/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|robots.txt|humans.txt|favicon.ico) {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-NginX-Proxy true;
            proxy_pass https://127.0.0.1:3000;
            #proxy_pass https://app_server;
            proxy_redirect off;
        }
    }

    include servers/*;
}

502 (Bad Gateway) errors

Funny fact: I have tried both to set up NGINX on Windows 2012 Server R2 and Ubuntu 16.04 LTS. On Windows, the same NGINX configuration file looks to work fine i.e. Not having these WebSocket connection errors below

1. Failed to load resource - 502 (Bad Gateway)

From Chrome Version 58.0.3029.110 (64-bit), I can access the web app file, but I am getting error for the websocket connections

/my-app/socket.io/?EIO=3&transport=polling&t=LmdtDAK&sid=xuUsA3zdwfQ9ShiXAAAA Failed to load resource: the server responded with a status of 502 (Bad Gateway)

2. GET 502 (Bad Gateway)

universalModuleDefinition:2 POST https://my.domain.com/my-app/socket.io/?EIO=3&transport=polling&t=LmdtEPE&sid=nWZYce-aUu0oSH-mAAAA 502 (Bad Gateway)
i.create @ universalModuleDefinition:2
i @ universalModuleDefinition:2
o.request @ universalModuleDefinition:2
o.doWrite @ universalModuleDefinition:2
(anonymous) @ universalModuleDefinition:2
(anonymous) @ universalModuleDefinition:2
o @ universalModuleDefinition:2
(anonymous) @ universalModuleDefinition:2
(anonymous) @ universalModuleDefinition:2
e.encodePacket @ universalModuleDefinition:2
i @ universalModuleDefinition:2
i @ universalModuleDefinition:2
c @ universalModuleDefinition:2
e.encodePayload @ universalModuleDefinition:2
n.write @ universalModuleDefinition:2
n.send @ universalModuleDefinition:2
n.flush @ universalModuleDefinition:2
n.onDrain @ universalModuleDefinition:2
(anonymous) @ universalModuleDefinition:2
n.emit @ universalModuleDefinition:2
r @ universalModuleDefinition:2
n.emit @ universalModuleDefinition:2
i.onSuccess @ universalModuleDefinition:2
i.onData @ universalModuleDefinition:2
i.onLoad @ universalModuleDefinition:2
hasXDR.r.onreadystatechange @ universalModuleDefinition:2

3. POST 502 (Bad Gateway)

POST https://my.domain.com/my-app/socket.io/?EIO=3&transport=polling&t=LmdtEPE&sid=nWZYce-aUu0oSH-mAAAA 502 (Bad Gateway)
i.create @ universalModuleDefinition:2
i @ universalModuleDefinition:2
o.request @ universalModuleDefinition:2
o.doWrite @ universalModuleDefinition:2
(anonymous) @ universalModuleDefinition:2
(anonymous) @ universalModuleDefinition:2
o @ universalModuleDefinition:2
(anonymous) @ universalModuleDefinition:2
(anonymous) @ universalModuleDefinition:2
e.encodePacket @ universalModuleDefinition:2
i @ universalModuleDefinition:2
i @ universalModuleDefinition:2
c @ universalModuleDefinition:2
e.encodePayload @ universalModuleDefinition:2
n.write @ universalModuleDefinition:2
n.send @ universalModuleDefinition:2
n.flush @ universalModuleDefinition:2
n.onDrain @ universalModuleDefinition:2
(anonymous) @ universalModuleDefinition:2
n.emit @ universalModuleDefinition:2
r @ universalModuleDefinition:2
n.emit @ universalModuleDefinition:2
i.onSuccess @ universalModuleDefinition:2
i.onData @ universalModuleDefinition:2
i.onLoad @ universalModuleDefinition:2
hasXDR.r.onreadystatechange @ universalModuleDefinition:2

Any pointers on what I may be doing wrong?

Different articles seems to concur, that I am doing the correct thing to upgrade HTTP connections to a WebSocket and does the NGINX doc.

Part of the problem, comes certainly that I am very new to NGINX and that I also don't understand what needs to be done in NGINX to reverse proxy the WebSocket connections. May be the fact that I am using a namespace is spicing things up a little. Any help and explanation will be appreciated.



via zabumba

Edge-Side Includes in Node and PHP

We are currently exploring microservices as our next architecture for a web app but we don't won't to limit that to the back-end. Self Contained Services (SCS) is what we want to implement, that means that the product is split in different components based on the business domain and contains all the back-end logic (REST API) and the front-end visualization (HTML, JS, CSS). Then, there are different pages comprised of many components. Each component belongs to a team, who is responsible for development and deployments, and NOT dependent on how other teams work. The problem is that the web app needs to be SEO optimized so including HTML on page load via async JS is not an option. I am looking for a way to do Edge-Side Includes (ESI) on the server (some pages are on Express Node server, others on Apache PHP), so the end result should be a pre-rendered page which looks something like this:

Server:
<esi:include src="http://snipets.com/get_component"></esi:include>

Client:
<script>some js</script>
<style>some css</style>
<div>some html</div>

There will be components included both in an Express Node app and Apache PHP



via Daniel Papukchiev

why react webport server port not conflict with node.js server port

I am running my react by using webpack-dev-server and script like this:

"build": "webpack -d && cp src/index.html ../personal_web_nodejs/views/index.ejs && webpack-dev-server --content-base src/ --inline --hot --history-api-fallback --port 8080",

I am putting it in port 8080. and after I run, the console shows: react console

However, I am also running my node.js server on 8080:

var port = normalizePort(process.env.PORT || '8080');

and the server can be run without saying the port is been used. node.hs console

I am kind of confused what exactly I am running? Anyone can explain me why and how I can run two servers with same port number?



via Lee

ajax getting the new data but not alwayes updating on the webpage

i working on a code to getting data from database for object position (sprite image ) and ajax should updating the position for object every 2 seconds and set pieces on the right position like the position on database but that's happend some time and sometime needs to refresh the page many times to get that so where's the problem I'm using node.js and javascript and html and jquery and json encode I don't get any error because any of them but I get the write position when I use console.log to check it in the client side or in server so are the error on the html or what ?

<!DOCTYPE html>
<html>

                <link rel="stylesheet" href="http://localhost:5000/cssFiles/styles.css"> 
                <title>JSChess</title>
                <link href="http://localhost:5000/cssFiles/styles.css" rel="stylesheet" type="text/css">
                <link rel="stylesheet" type="text/css" href="http://localhost:5000/cssFiles/styles.css" />

<body>


                <h2>Welcome <span style="color:green"><h1>your nam</h1>! </span>You are playing against <span style="color:red"><h1>your nam</h1>! </span>
                </h2>   
                <div id="FenInDiv" style="display:none;">           
                    <input type="text" id="fenIn"/>     
                    <button type="button" id="SetFen">Set Position</button> 
                </div>  
                <div id="ThinkingImageDiv">     
                </div>
                <div id="Board">
                </div>
                <div id="CurrentFenDiv" >
                    <span id="currentFenSpan" style="display:none;"></span>     
                </div>              
                <div id="ChatMessages">
                </div>
                <div id="AvailablePlayers"></div>

                <div id="ChatMessages"></div>
                <div id="ChatBig"> 
                    <span style="color:green">Chat</span><br/>
                    <textarea id="ChatText" name="ChatText"></textarea>
                </div>
                <button type="button" id="NewGameButton">New Game</button><br/>
                <span id="GameStatus"></span>
        <!--This div not outputted but needed to work  -->          
                <div id="EngineOutput"><br/>
                    <select id="ThinkTimeChoice" style="display:none;">
                    <option value="1">1s</option>
                    <option value="2">2s</option>
                    <option value="4">4s</option>
                    <option value="6">6s</option>
                    <option value="8">8s</option>
                    <option value="10">10s</option>
                    </select><br/><br/><br/>

                    <span id="BestOut" style="display:none;">BestMove:</span><br/>
                    <span id="DepthOut"style="display:none;">Depth:</span><br/>
                    <span id="ScoreOut"style="display:none;">Score:</span><br/>
                    <span id="NodesOut"style="display:none;">Nodes:</span><br/>
                    <span id="OrderingOut"style="display:none;">Ordering:</span><br/>
                    <span id="TimeOut"style="display:none;">Time:</span><br/><br/>
                    <button type="button" id="SearchButton"style="display:none;">Move Now</button><br/>

                    <button type="button" id="FlipButton"style="display:none;">Flip Board</button><br/><br/>
                    <button type="button" id="TakeButton"style="display:none;">Take Back</button><br/><br/><br/>

                </div>


                <script src="js/jquery-3.2.1.min.js"></script>  

                <script src="js/defs.js"></script>
                <script src="js/io.js"></script>
                <script src="js/board.js"></script>
                <script src="js/movegen.js"></script>
                <script src="js/makemove.js"></script>
                <script src="js/perft.js"></script>
                <script src="js/evaluate.js"></script>
                <script src="js/pvtable.js"></script>
                <script src="js/search.js"></script>
                <script src="js/protocol.js"></script>       
                <script src="js/guiMultiPlayer.js"></script>
                <script src="js/main.js"></script>
                <script src="js/deleteDB.js"></script>
               <script src="/socket.io/socket.io.js"></script>


</body>
</html>

the javascript ajax part

function loadLMove(){ 


        $.ajax({
            type:'POST',
            url:'/dispalymove',
            data:{MoveString:MoveString},
            dataType:'json',
            cache: false,
            //timeout: 20000,
            success:function(data){
                if (data.msg != ""){
                    if (MoveString!=data.msg){
                        var now = new Date().getTime();
                        //alert(data.msg);
                        ParseFen(data.msg);
                        ++timesRun;
                         console.log('Move displayed: ' + data.msg + 'Action ' + timesRun + ' started ' + (now - startTime) + 'ms after script start');
                        //PrintBoard();     
                        SetInitialBoardPieces();    
                        GameController.PlayerSide = brd_side;   
                        CheckAndSet();  

                        EvalPosition(); 
                        //PerftTest(5);
                        //newGameAjax();
                        MoveString=data.msg;
                        }
                } else{
                    if (MoveString!=data.msg){
                        ParseFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
                        //PrintBoard();     
                        SetInitialBoardPieces();    
                        GameController.PlayerSide = brd_side;   
                        CheckAndSet();  

                        EvalPosition(); 
                        //PerftTest(5);
                        //newGameAjax();
                    }
                }
            }
        });

}
//---------------------------------------------------------
loadLMove();
setInterval(loadLMove,2000);

my node.js code

app.post('/dispalymove', function (req, res, next) {
var lMove="";
if(req.body.MoveString !== null){

     Move.setMoveUserId(req.user.id);
     Move.setMoveString(req.body.MoveString);
     a.getLastMove(req.user.GameId,function(move){
      console.log("Return from display req.body:",req.body.MoveString);
      console.log("Return from display themove:",move);
        res.json({"msg": move, "loggedin": "true"});

      });


    } else {

              var output = {"msg": lMove, "loggedin": "true"}; // <=== here  always equals ""

               res.json(output);

    }


});

getlastmove function code

getLastMove(id,callback){


        var MoveRequest = "SELECT * FROM users ORDER BY id";    
        var query = connection.query(MoveRequest, function(err,rows, result) {
        if (rows.length == 0) { 
            return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
        }
        if (rows.length > 0) {
            for (var i in rows) {

                var move = rows[i].MoveString; 
                if (rows[i].GameId == id){

                    callback(move);
                    return;
                }

            }
        }

        });


    }



via dark night

Installing Mathoid (MediaWiki) on centos 6.8

I am preparing Mediawiki and Mathoid on Centos 6.8 (i am using CodeAnyWhere.com free service).

Please see, https://www.mediawiki.org/wiki/Mathoid

I get some errors when i run below command:

npm install mathoid

I am beginner to linux and nodejs configurations. please advise me



via SKMohammadi

How to fix npm update error? (# npm install npm@latest -g)

How to fix npm update error? I run as root

# npm install npm@latest -g

usr/lib
└── (empty)

npm ERR! Linux 4.10.14-200.fc25.x86_64
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "npm@latest" "-g"
npm ERR! node v6.10.2
npm ERR! npm  v3.10.10
npm ERR! path /usr/lib/node_modules/npm/node_modules/node-gyp
npm ERR! code EEXIST
npm ERR! errno -17
npm ERR! syscall mkdir

npm ERR! EEXIST: file already exists, mkdir '/usr/lib/node_modules/npm/node_modules/node-gyp'
npm ERR! File exists: /usr/lib/node_modules/npm/node_modules/node-gyp
npm ERR! Move it away, and try again.

npm ERR! Please include the following file with any support request:
npm ERR!     /root/npm-debug.log
npm ERR! code 1

And end up without npm.

The log file is at https://pastebin.com/UuWNhNwe

my node version is 6.10.2, using fedora core 25 64bits



via Pedro Polonia

Aggregating models "through" other models in SQL?

I have a sequelize based backend express API. In my sequelize models, a Citizen belongs to a Street which belongs to a Town, which belongs to a State. I can count the citizens in a Street easily like:

return db.Citizen.aggregate('value', 'count', {
    where: { 
         '$Town.name$': townName
    },
});

However, I would like to be able to count the citizens in a Town or State, even though Citizens aren't directly associated with those models. Is that possible and if so, how could I do it?



via George Edwards

Cordova app ajax call to localhost fails. ::ERR_CONNECTION_REFUSED

I've got an node.js (express) webapp running on localhost:3000. I am now trying to develop a mobile app using cordova.

I've got a route defined in my express app 'localhost:3000/tweets' which when called gets some tweets using twitter API and send them back as json object. Everythinngs works very fine using web app however I am struggling to make the same ajax call from a mobile app. To allow requests from other hosts I've added this to my edxpress app.js:

    app.use(function(req, res, next) {
       res.header('Access-Control-Allow-Origin', "*");
       res.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');
       res.header('Access-Control-Allow-Headers', 'Content-Type'); next();
    });

(I'm not sure thats the correct way to allow conenctions from others hots but that seem to work)

In my cordova app:

meta tag:

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">

config.xml

    <?xml version='1.0' encoding='utf-8'?>
<widget id="<id...>" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>appname</name>
    <description>
        A twitter search app.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <access origin="*" />
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
    <engine name="android" spec="^6.2.3" />
    <plugin name="cordova-plugin-camera" spec="^2.4.1" />
    <plugin name="cordova-plugin-whitelist" spec="^1.3.2" />
</widget>

In the index.html file i link 'querySender.js' file at the bottom of body:

    <script type="text/javascript" src="js/querySender.js"></script>

And finally, content of 'querySedner.js'

$(document).ready(function(){

  $('#btn_send').on('click', function(){
    console.log("app is now sending query!");
    $.ajax({
        type: 'POST',
        url: 'http://127.0.0.1:3000/tweets',
        data: {name:"test_name",lastname:"last_name"},
        dataType:'json',
        success: function(dataR){
          var date = new Date();
          console.log("POST success recorded at: ",date.getTime());
          if (!dataR){
          console.log("No Data received");
          }else{
              console.log("DataR: ",dataR);
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          console.log("Status: " + textStatus+" error:"+ errorThrown);
        },
        timeout:5000
      });

  });
});

using WebStrom IDE i tried to run index.html in chrome (it runs it on localhost:63342) the request succeeds and data is delivered as expected.

however is emulate the app using android emulator when i press the button i get:

POST http://127.0.0.1:3000/tweets net::ERR_CONNECTION_REFUSED -- jquery-3.2.1.min.js:4

Basically. I'm running my node.js(express) server locally and would like to make ajax calls to it from cordova app on android emulator. What did I get wrong?



via EasternDude

Deploying create-react-app express api to heroku

I have an app that uses a React/Redux client (generated by create-react-app) and it communicates with a Node/Express api. When I run this during development, it works perfectly.

I just deployed to Heroku for the first time however, and only the client side of my app is working. I get error messages in the console that the api routes return a 404.

Any ideas on how to solve this? I think it must be something simple like adding a script to package.json.



via JohnSnow

Generating rooms with Node.js / Socket.io

Some browser games like agar.io and generals.io have a feature in which a player can create a private game room associated with a link. Other players can join the room by going to the same link in their browser. How does this feature work and could I replicate it using Socket.io and Node.js?



via Simon Huang

Why mongoose query with promise always goes to .then block rather than .catch

my User collection have one user and that is inactive but when I query to find out the user which is Exist and Active, I am using mongoose 4.x with promise (see below query) , it always goes to .then block and display blank array but in my understanding, it must go to .catch()block.

Please correct me and suggest how to write the right query.

Schema

let userSchema = new Schema({
    username: {type: String, required: true, unique: true},
    password: {type: String, required: true},
    firstName: {type: String, required: true},
    lastName: {type: String},
    email: {type: String, required: true},
    gender: {type: String, enum: ['M','F'], default: 'M'},
    passwordReset: {type: Boolean, default: false},
    isActive: {type: Boolean, default: false},
    createdOn: {type: Date, default: Date.now}
});

query

User
            .find()
            .and([{username: req.body.username}, {isActive: true}])
            .exec()
            .then( (user) => {
                    console.log('user found', user );
                    // match saved and input password
                    if (user.password === req.body.password) {
                        res.status(200).json(user);
                    } else {
                        console.log('else part', user);
                        res.status(404).send({
                            "message": "invalid credentials."
                        });
                    }
                }).catch( (err) => {
                    console.log('catch error', err);
                    res.status(404).send(err);
                });
        }



via pro.mean

Backend api vs database (as a service)

I'm building an app with shared realtime data that users can edit.

However should I build a backend service (feathers/sails) or simply use a database (pouchdb/rethinkdb/deepstream)?

Many thanks



via Cooltrooper

Extracting file icon and display in html

Evening Everyone,

I have started doing some research for an application i want to write using the electron framework. I have figured out how to display what i want to the user with the exception of the icons. There is a part of the application where the user can type a path and it will list the files in that path, i would like to pull the icon from the files so its displayed just like it would be in the windows file explorer. This is where i have been running into a roadblock and I'm looking for some guidance.

Is there a method in nodejs that would allow me to provide a file path and in return get a image back i can pass to HTML? Im new to nodejs so i figured i would ask and see if anyone knew of an easy way.



via Zachary Shupp

express+nodejs routes aren't working under node-webkit/nw.js

I have made a really simple app using guidebox api with guidebox node library. My code is working completely fine when I run the app inside browser but when I try to package it with node-webkit/nw.js it doesn't return any results or show anything.

What have I done till now? I tried to use the sdk version of nw.js to debug the app. The only thing I could find in console was this and I didn't understand a bit of it. Why it is showing like this. Also, why there is an error in routes ?

chrome-extension//...something/searchContent/search=fun

enter image description here

guidebox.js // client side script

    $('#searchTerm').on('submit', function(e) { // search movies
    e.preventDefault();
    $('#searchResults').empty();
    var query = $('#inputField').val();
    $.ajax({
        type: 'GET',
        data: { search: query },
        url: '/searchContent',
        success: function(data) {
            for (var i = 0; i < data.results.length; i++) {
                var source = data.results[i].poster_120x171;
                var img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img'))
                img.attr('src', source);
                img.appendTo('#searchResults');
            }
            console.log(data);
        }
    });
});


$('#getMoviesButton').on('click', function() { // get latest movies
    $('#movieResults').empty();
    $.ajax({
        type: "GET",
        url: "/getMovies",
        dataType: 'JSON',
        success: function(data) {
            for (var i = 0; i < data.results.length; i++) {
                var source = data.results[i].poster_120x171;
                var img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img'))
                img.attr('src', source);
                img.appendTo('#movieResults');
            }
        }
    });
});

app.js // server side

` 
// init project
var express = require('express'),
    path = require('path'),
    app = express(),
    Guidebox = require('guidebox')('ca49220ce9cfc67411c43a9074c99353579ef6de', 'JP'),
    __dirname = "";

// we've started you off with Express, 
// but feel free to use whatever libs or frameworks you'd like through `package.json`.

// http://expressjs.com/en/starter/static-files.html 
app.use(express.static(path.join(__dirname, '../GuideBox')));

// http://expressjs.com/en/starter/basic-routing.html
app.get("/", function(request, response) {
    // response.sendFile(__dirname + '/views/index.html'); 
    response.sendFile('index.html', { root: path.join(__dirname, '../GuideBox') });
});

app.get("/searchContent", function(req, res) {
    var searchQuery = req.query.search;
    console.log(searchQuery);
    Guidebox.search.movies({ field: 'title', query: searchQuery })
        .then(function(data) {
            res.send(data);
        });
});


app.get("/getMovies", function(req, res) {
    Guidebox.movies.list()
        .then(function(data) {
            res.send(data);
        })
        .catch(function(e) {
            console.log(e);
        });
});

app.listen(3030);
console.log("my server is running...");
`

index.html // front end ui

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Guide Box Demo</title>
    <link rel="stylesheet" href="css/custom.css">
    <script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
</head>

<body>
    <div>
        <h1>GUIDEBOX DEMO</h1>
    </div>
    <div id="col-one" class="widthClass">
        <form id="searchTerm">
            <input type="text" id="inputField" name="search" placeholder="search content here... " maxlength="120">
            <button type="submit" id="searchButton"><b>SEARCH</b></button>
        </form>
        <br>
        <br>
        <br>
        <div>
            SEARCH RESULTS:
            <br>
            <div id="searchResults"></div>
        </div>
    </div>
    <div id="col-two" class="widthClass">
        <button type="submit" id="getMoviesButton" value="MOVIES"><b>GET MOVIES</b></button>
        <br>
        <br>
        <br>
        <div>
            MOVIES RESULTS:
            <div id="movieResults"></div>
        </div>
    </div>
    <script type="text/javascript" src="js/guideBox.js"></script> 
</body>

</html>



via Ryder

message: middlewareError - nodejs

I uploaded a nodejs application to an ec2 AWS ubuntu instance. After some time online it doesn't respond anymore.

Now I installed winston to log errors and got the following:

{
  "date": "Sat May 20 2017 19:41:23 GMT+0000 (UTC)",
  "process": {
    "pid": 6740,
    "uid": 1000,
    "gid": 1000,
    "cwd": "/home/ubuntu/www",
    "execPath": "/usr/bin/nodejs",
    "version": "v4.2.6",
    "argv": [
      "/usr/bin/nodejs",
      "/home/ubuntu/www/server/app.js"
    ],
    "memoryUsage": {
      "rss": 95809536,
      "heapTotal": 68333664,
      "heapUsed": 65639712
    }
  },
  "os": {
    "loadavg": [
      0.046875,
      0.04931640625,
      0.0263671875
    ],
    "uptime": 33009
  },
  "trace": [],
  "req": {
    "url": "/users/me",
    "headers": {
      "host": "api.example.com",
      "connection": "keep-alive",
      "accept": "application/json, text/plain, */*",
      "origin": "http://example.com",
      "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
      "referer": "http://example.com/",
      "accept-encoding": "gzip, deflate, sdch",
      "accept-language": "en-US,en;q=0.8"
    },
    "method": "GET",
    "httpVersion": "1.1",
    "originalUrl": "/users/me",
    "query": {}
  },
  "level": "error",
  "message": "middlewareError"
}

The error message middlewareError is not really clear to me. It seems like there is a memory problem? If thats the case, can anyone point me in the right direction how to dig into this?



via Stefan

Handling nested async / await calls

Trying to learn the async pattern in Javascript but it doesn't appear that it waits for the following line. In the following example, the collection is the request object and not the actual parsed body. Isn't await supposed to wait for the request to finish?

async function importUsers(endpoint) {
    const options = {
        data: search,
        uri: endpointCollection,
        headers,
    }

    try {
        const collection = await browser.post(options, (err, res, body) => JSON.parse(body))
        const users = await collection.data.forEach(item => parseUserProfile(item));

        await users.forEach(user => saveUserInfo(user))
    } catch(err) {
        handleError(err)
    }
}



async function parseUserProfile({ username, userid }) {
    const url = userProfileString(username)

    try {
        const profile = await browser.get(url, headers, (err, res, body) => {   
            return { ... } // data from the body
        })
    } catch(err) {
        handleError(err)
    }
}



via user3162553

Hiding fetch request keys

I am using the new OMDB api, and want to keep the fetch requests (that include the key) out of visibility on client-side.

Here is an example of the problem whenever a user opens up dev tools:feelsbad.

I do all my calls in React like so:

  import OmdbKey from './OmdbKey';
  populate(keystrokes) {
    let query = "http://www.omdbapi.com/?s=";
    fetch(query + keystrokes + '&apikey=' + OmdbKey )
      .then((response) => {
        response.json().then((json) => {
          this.setState({ results: json.Search });
        });
      });
  }

Is there some way to do this so I can hide the key in the GET request? How else should I approach this if not?

Thanks



via user3335607

Can't create socket server from http module

I wanna create socket server like a Socket.io because socket.io can't work with Corona SDK. So I need custom socket server. I create socket server with using net module and it is work good. But I need using http module because I write REST API. I try create sample socket server from http module but have errors.

var net = require('net');
var HOST = 'localhost';
var PORT = 9999;

var server = require('http').createServer(function(request, response) {
    response.end('Hello from server');
});

server.on('connection', function(socket) {
    socket.on('data', function(data) {
        data = data.toString('utf-8');

        console.log(data);

        socket.write('Hello from server');
    });

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

server.listen(PORT, HOST);

var client = new net.Socket();
client.connect(PORT, HOST, function() {
    console.log('CONNECTED TO: ' + HOST + ':' + PORT);

    client.write('I am Chuck Norris!');
});

client.on('data', function(data) {
    console.log('DATA: ' + data);

    client.destroy();
});

client.on('close', function() {
    console.log('Connection closed');
});

If I run this script I got error:

CONNECTED TO: localhost:9999
I am Chuck Norris!
Error: This socket is closed
    at Socket._writeGeneric (net.js:692:19)
    at Socket._write (net.js:743:8)
    at doWrite (_stream_writable.js:329:12)
    at writeOrBuffer (_stream_writable.js:315:5)
    at Socket.Writable.write (_stream_writable.js:241:11)
    at Socket.write (net.js:670:40)
    at Socket.<anonymous> (/var/work/projects/edorium/Server/test/test.js:49:16)
    at emitOne (events.js:101:20)
    at Socket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
{ Error: Parse Error
    at socketOnData (_http_server.js:411:20)
    at emitOne (events.js:101:20)
    at Socket.emit (events.js:191:7)
    at readableAddChunk (_stream_readable.js:178:18)
    at Socket.Readable.push (_stream_readable.js:136:10)
    at TCP.onread (net.js:560:20) bytesParsed: 0, code: 'HPE_INVALID_METHOD' }
Connection closed

Why this happed and how fix this?



via Metal Evolution Studio

How to Get Window Variable Using WebdriverIO

I am trying to run webdriverio with PhantomJS/Chrome to load a page and then grab the window object for use with other scripts. For some reason I am unable to get the window object. Everytime I get, I end up seeing output like this:

Title is: XXXXX
{ state: 'pending' }

Using the following script:

var webdriverio = require('webdriverio');
var options = {
    desiredCapabilities: {
        browserName: 'chrome',
        logLevel: 'verbose'
    }
};

var client = webdriverio.remote(options);

client
     .init()
     .url('https://xxxx.com')
     .waitUntil(function () {
         return client.execute(function () {
             return Date.now() - window.performance.timing.loadEventEnd > 40000;
        }).then(function (result) {
             console.log(window);
             return window;
         });
     })
     .end();

Does anyone know how I can fix my code so that the window object is returned to my NodeJS console app after the page is completely loaded?

Thanks!



via user2476265

How to do mouse hover using selenium webdriver/node.js/mocha?

I have tried following code: client.findElement(webdriver.By.xpath("xpath")).click(). However, it's not working. I am using selenium webdriver with node.js on mocha framework.



via Monika Pathak

How to parse a string into JSON that (I think) contains arrays

Given a string that is appears to be in valid JSON format (received from an api call), how can I parse that string such that I can get access to

The value of JSON.parse(data) comes back as JSON that contains [Object], which is not helpful to me.
I'm trying to get the lat and lng out of data that is sent to me as a string that I think can be turned into JSON.
I know I could just mess around with data as a string, but I want to use it as JSON.

{ results: 
   [ { address_components: [Object],
       formatted_address: 'Google Bldg 41, 1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA',
       geometry: [Object],
       place_id: 'ChIJxQvW8wK6j4AR3ukttGy3w2s',
       types: [Object] } ],
  status: 'OK' }

Here is the value of data:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Google Building 41",
               "short_name" : "Google Bldg 41",
               "types" : [ "premise" ]
            },
            {
               "long_name" : "1600",
               "short_name" : "1600",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Amphitheatre Parkway",
               "short_name" : "Amphitheatre Pkwy",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Mountain View",
               "short_name" : "Mountain View",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Santa Clara County",
               "short_name" : "Santa Clara County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "California",
               "short_name" : "CA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "94043",
               "short_name" : "94043",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "Google Bldg 41, 1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 37.4228642,
                  "lng" : -122.0851557
               },
               "southwest" : {
                  "lat" : 37.4221145,
                  "lng" : -122.0859841
               }
            },
            "location" : {
               "lat" : 37.4224082,
               "lng" : -122.0856086
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 37.4238383302915,
                  "lng" : -122.0842209197085
               },
               "southwest" : {
                  "lat" : 37.4211403697085,
                  "lng" : -122.0869188802915
               }
            }
         },
         "place_id" : "ChIJxQvW8wK6j4AR3ukttGy3w2s",
         "types" : [ "premise" ]
      }
   ],
   "status" : "OK"
}



via Glen Pierce

Cordova does not install, path error

Hy,

I'm trying to install "cordova" but I always get this error:

https://s14.postimg.org/4oxgcgiox/cordova_errore.png

This is my system computer variables :

https://s14.postimg.org/n5rv39yn5/variabili_d_ambiente_sistema.png

I use window 10 64 bit and node.js is alredy installed.

Have any solution ?



via Odixx

app.use middleware doesn't execute for routes

I am following this tutorial and I want to do something similiar, when my user access other routes diferents then register and login I want him to send the token to give the access to those routes.

If I do a request to /login or /register everyhting fine.

But when I do a request to /fotos, my app.use(jwtPermission); should be executed.

Here is my app server initial page:

var jwt = require('jsonwebtoken');
var jwtPermission = require('./controller/jwtPermission');
var fotos = require('./routes/fotos');
var app = express();
var router = express.Router();


// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use('/',require('./routes/index'));
app.use(jwtPermission);
app.use('/fotos',fotos);

my jwtPermission file is inside the controller, this controller folder is at the same level then my server initial start file.

Here is what I have in my jwtPermission:

var jwt = require('jsonwebtoken');
var jwtConfig = require('../config/jwt');

module.exports = function(req, res, next) {
    console.log("entered");

    // check header or url parameters or post parameters for token
    var token = req.body.token || req.query.token || req.headers['x-access-token'];
          console.log(req.headers['x-access-token']);
    // decode token
    if (token) {
        // verifies secret and checks exp
        jwt.verify(token,jwtConfig.secret, function (err, decoded) {
            if (err) {
                return res.json({ success: false, message: 'Failed to authenticate token.' });
            } else {
                // if everything is good, save to request for use in other routes
                req.decoded = decoded;
                next();
            }
        });
    } else {
        // if there is no token
        // return an error
        return res.status(403).send({
            success: false,
            message: 'No token provided.'
        });
    }
}

if I point to /fotos it never reaches the jwtPermission file, if I change the app.use(jwtPermission) above my register app.use, it works, but the middleware get called for all routes including the /register /login.

Need some help please :).

Thanks!



via Cris dois