Saturday, 8 April 2017

NodeJS Express: CORS enabled and still not working

I'm having a huge problem with CORS.
I'm developing in AngularJS using NodeJS Express and I have another API running in another IP/PORT (both are in the same machine). I'm coding functions in Angular to consume the API.

When I try to get/post/delete/put I receive this message:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:3000' is therefore not allowed access.

There's a lot of solutions here in Stackoverflow to configure the app.js. One configuration that I've tried and still not working:

app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});  

I have installed the npm cors module. I've edited my app.js to enable the cors module and still not working:

var express = require('express');
var cors = require('cors');  
app.use(cors());  

Any solutions? I have no idea how to fix it! Btw I'm using Chrome.



via Victor

How to use an angular test file?

I have a test file like what is at the end. I have tried node FILENAME, npm FILENAME, which get me errors. I've also tried npm test which seem to test something else (attached after the testing file). I'm new to angular and looked at the demo but, Im not really sure what I should be doing.

Code from here: https://github.com/vega/vega-lite-ui (not mine)

testing file:

'use strict';

/* global vl:true */

describe('Directive: bookmarkList', function () {
  var element,
    scope;

  afterEach(inject(function(Modals) {
    // Remove any modals registered during the tests
    Modals.empty();
  }));

  beforeEach(module('vlui', function($provide) {
    // mock vega lite
    $provide.constant('vl', vl);
  }));

  beforeEach(inject(function ($rootScope) {
    scope = $rootScope.$new();
    scope.active = true;
  }));

  it('requires a parent modal directive', inject(function ($compile) {
    // This is a side-effect of the modalCloseButton directive inside bookmarkList
    element = angular.element('<bookmark-list></bookmark-list>');
    expect(function() {
      $compile(element)(scope);
    }).to.throw;
    element = angular.element('<modal><bookmark-list></bookmark-list></modal>');
    expect(function() {
      $compile(element)(scope);
    }).not.to.throw;
  }));

  describe('when opened', function() {
    beforeEach(inject(function(Modals, $compile) {
      var template = '<modal id="test-bookmarks"><bookmark-list></bookmark-list></modal>';
      element = $compile(angular.element(template))(scope);
      Modals.open('test-bookmarks');
      scope.$digest();
    }));

    // TODO: Tests that validate the directive works properly
  });
});

npm test results:

START:
09 04 2017 01:03:39.411:WARN [watcher]: Pattern "/Users/me/psa/polestar/src/vendor/*.js" does not match any file.
09 04 2017 01:03:39.522:INFO [karma]: Karma v1.6.0 server started at http://0.0.0.0:9875/
09 04 2017 01:03:39.523:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
09 04 2017 01:03:39.531:INFO [launcher]: Starting browser PhantomJS
09 04 2017 01:03:40.644:INFO [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Connected on socket BU46HqpjWzeEkmYvAAAA with id 72055404
  Service: Spec
    ✔ should be defined
    ✔ functions should be defined
    _removeEmptyFieldDefs
      empty spec
        ✔ should be cleaned
  Directive: configurationEditor
    ✔ should insert form
    ✔ should attach config to scope
  Directive: jsonInput
    ✔ should make hidden element visible
  Directive: lyraExport
    ✔ should make hidden element visible
  Directive: vgSpecEditor
    ✔ should show source code
  Directive: vlSpecEditor
    ✔ should show source code

Finished in 0.26 secs / 0.066 secs

SUMMARY:
✔ 9 tests completed
[01:03:41] Finished 'test' after 2.17 s



via Bren

How to count all entires of recyclerview list in android app using Appium

In the app I am automating using appium+node.js, the screen with Offers has recycler view for offer list. Each cell is an image without any text on it.

I am getting the total count of offers through API call and want to assert that count by counting the total list entries.

enter image description here

Currently I am only able to get count of elements displayed on the screen(i.e 3 in this case).

How can I count each entry of this section and match that count with the total count of api result?



via Shashi Kumar Raja

Exception from Tracker recompute function and sub user id, Match error

I have a user publish and subscribe problem. When I click on a user name, it is supposed to show: [1] user's profile image; and [2] all posts from that user.

However it just shows a loading spinner screen and the below errors. If I try a couple of refresh or re-clicking the name, the page eventually loads with some lag.

I suspect a client race condition but I tried adding a (!this._id) return [ ] or this.ready();, the posts would flash on screen once and not show up thereafter. I cant remove the check as it throws a no check error.

If theres anywhere to simplify showing posts of the user, please kindly advise. Thanks!

error on the browser console:

Exception from Tracker recompute function: meteor.js:930:11

undefined meteor.js:932:11

selected portions of the key error shown on terminal:

> I20170409-11:51:58.787(8)? Exception from sub user id
> BRFKAiwEXKootpbwY Error: Match error: Expected string, got null
> (packages/check/match.js:34:1) I20170409-11:51:58.788(8)?     at
> Subscription.<anonymous> (server/server.js:86:2)
> I20170409-11:51:58.788(8)?     at Subscription.prepareOptions
> (packages/reywood_publish-composite/packages/reywood_publish-composite.js:440:1)
> I20170409-11:51:58.788(8)?     at Subscription._handler
> (packages/reywood_publish-composite/packages/reywood_publish-composite.js:408:1)
> I20170409-11:51:58.788(8)?     at packages/check/match.js:107:1 
> at Object.exports.Match._failIfArgumentsAreNotAllChecked
> (packages/check/match.js:106:1) I20170409-11:51:58.788(8)?     at
> maybeAuditArgumentChecks
> Match failed [400]

The server publish

Meteor.publish('userDetails', function() {
    var fields = { 
        username    : 1, 
        emails      : 1, 
        profile     : 1,
        md5hash     : 1 
    };
    return Meteor.users.find( {}, { fields: fields });
});

Meteor.publishComposite('user', function (_id) {
    check(_id, String);  // cant remove this check, throws error
    //if (!this._id)  return this.ready(); or [] doesnt work 
        return {
            find: function() {
                return Meteor.users.find({ _id: _id }, { 
                    fields: { 
                        username    : 1, 
                        emails      : 1, 
                        profile     : 1,
                        md5hash     : 1 
                    }
                });
            },
                children: [
                    { 
                        find: function(user) { 
                            return Posts.find({ userId: user._id }); 
                        } 
                    } 
                ]
        };
});

Router code

Router.route('/users/:_id',      { 
  name: 'users.show',     
   onBeforeAction: function () {
      if( this.params._id === Meteor.userId() ){ 
         Router.go('profile');
      } else {
         this.next();
      }
   }
});

the page js

Template.usersShow.onCreated(function(){
   var self = this;
   self.autorun(function(){
      self.subscribe('user', Router.current().params._id);
   });
});
Template.usersShow.helpers({
   user: function () {
      return Meteor.users.findOne({ _id: Router.current().params._id });
   },
   posts: function () {
      return Posts.find({ userId: Router.current().params._id });
   }
});



via Thinkerer

Change font color per client/browser using node.js websocket

I'm trying to create a online chat application using websocket for node.js. Right now it is working but I want to extend the functionality so that when I open it from another browser(client) it will generate a different color text so i can easily distinguish who is who. So far I have this code.

Thanks!

<!--index.html-->
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="minimum-scale=1.0, width=device-width, maximum-scale=1.0, user-scalable=no"/>
    <meta charset="utf-8">
    <title>Websocket</title>
    <link rel="stylesheet" href="style.css"/>
</head>
<body>
<h1>Websocket</h1>
<div class="messages"></div>
<form action="javascript:void(0)">
    <label for="message">&gt;</label>
    <input type="text" id="message" required autofocus />
</form>
<script src="ws-client.js"></script>
</body>
</html>

style.css

body {
    background-color: black;
    color: #0F0;
    font-family: verdana;
}

body input,
body label {
    display: block;
}

h1 {
    text-align: center;
}


input {
    outline: none;
    border: none;
    background-color: black;
    color: #0F0;
    padding: 1em .5em;
    display: block;
    font-size: 1.5em;
    -webkit-box-flex: 1;
    -webkit-flex-grow: 1;
    -ms-flex-positive: 1;
    flex-grow: 1;
}

label {
    display: block;
    padding: 1em .5em;
    font-size: 1.5em;
}

div.messages {
    margin-left: 1em;
}

form {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
}

ws.js

var WebSocketServer = require("ws").Server; 
var wss = new WebSocketServer({ port: 3000 }); 

wss.on("connection", function(ws) {
    ws.on("message", function (message)
    {
        if (message === 'exit'){
            ws.close();
        } else{
            wss.clients.forEach(function(client) {
                client.send(message);
            });
        }       
    });
    ws.send("Welcome to cyber chat");
});

ws-client.js

var ws = new WebSocket("ws://localhost:3000");

ws.onopen = function(){
    setTitle("Connected with chat");
};

ws.onclose=function(){
    setTitle("null");
};

ws.onmessage=function(payload){
    printMessage(payload.data);
};

document.forms[0].onsubmit = function () {
    var input = document.getElementById('message');
    ws.send(input.value);
    input.value = '';
};

function setTitle(title) {
    document.querySelector('h1').innerHTML = title;
}

function printMessage(message) {
    var p = document.createElement('p');
    p.innerText = message;
    document.querySelector('div.messages').appendChild(p);
}



via user7836693

Running node.js within Xcode Project

So I have we already have push notifications set up and an apns.js file created that when I run "node apns.js" on terminal, it sends a push notification. I want to be able to run that apns.js from within the Xcode app by clicking a button. Does anyone know how to do this? I assume it can't be too many lines of code to add in the view controller for the button since push notifications are already set up in app delegate. All the tutorials I found online required that I run the command script in terminal, but I need to do that on the actual mobile application. The app is connected to an FTP (File Transfer Protocol) using cyberduck where the apns.js file is saved and MySQL database too. Any help would be great i'm kinda stuck with this issue.



via Zane Habib

serverless framework sls Conflits with Powershell sls (Select-string)

I installed the Serverless Framework using the following NPM command

npm install -g serverless

When I try to run the serverless command sls in Powershell , I get a strange result which mentions "cmdlet Select-string".

sls --version

enter image description here

Can someone help me with this issue?



via Mike Barlow - BarDev

Mongoose, populate where an ID is specific to a project reference

I m trying to populate a mongoose model where I only want the returned items to be the ones that are matched with an ID.

//Partial Schema

task: [{
    projectID: {
      type: String
    },
    theTask: {
      type: Schema.Types.ObjectId,
      ref: "Task" 
    }
  }]

How can I only get the task populated where the projectID is equal to a specific ID. I tried

User.findById({ "_id": req.params.id }).populate({ path: 'task', match: {projectID: req.params.pID}, select: 'theTask' })
  .exec(function(err, docs){
    console.log("POPULATE TASKS DOCS", docs)

But this is showing that the docs is empty.



via henhen

Running yarn scripts in webstorm with non-system node binary

I'm attempting to use webstorm for a new project and use yarn instead of npm. However, after generating the project I can't get the scripts to run via yarn. My start script has the following run configuration in WebStorm.

package.json: ~/dev/starting_sandbox/package.json

Command: run

Scripts: start

Node Interpreter: ~/.nvm/versions/node/v7.8.0/bin/node

Npm package: ~/.nvm/versions/node/v7.8.0/lib/node_modules/yarn

~~~

When this runs I get an error:

/Users/byronsm/.nvm/versions/node/v7.8.0/bin/node /Users/byronsm/.nvm/versions/node/v7.8.0/lib/node_modules/yarn/bin/yarn.js run start
yarn run v0.21.3
$ react-scripts start 

~/dev/starting_sandbox/node_modules/cross-spawn/index.js:34
            throw new Error(
                  ^
Error: In order to use spawnSync on node 0.10 or older, you must install spawn-sync:

  npm install spawn-sync --save
    at Function.spawnSync [as sync] (~/dev/starting_sandbox/node_modules/cross-spawn/index.js:34:19)
    at Object.<anonymous> (~/dev/starting_sandbox/node_modules/react-scripts/bin/react-scripts.js:22:22)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:929:3
error Command failed with exit code 8.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I was able to solve this problem in webpack when running the scripts via npm by using the --scripts-prepend-node-path option. However, this doesn't seem to exist for yarn.

This seems to be an issue with the instance of node that yarn runs when executing the scripts, instead of pulling from the same node binary used to execute yarn itself, it uses what it finds in $PATH, which isn't modified.

Is there a similar command you can use for yarn?



via Krustal

response.render() not rendering correct page

I have a form on one page. I am trying to submit that form and send that data to a new page. However, response.render() is not rendering the new page, instead the page with the form on it is just being reloaded.

page with form = historicalReport.ejs, new page = historicalReportGraph.ejs

This is the code to submit the form in historicalReport.ejs

$("#newHistoricalReportForm").validate({
  rules: {
    latitude: {
      required: true
    }, 
    longitude: {
      required: true
    }, 
    year: {
      required: true
    },
    ppm_type: {
      required: true
    }
  },
  submitHandler: function(form) {
    submitNewHistoricalReportForm();
  }
});
function submitNewHistoricalReportForm() {
    var form = document.getElementById("newHistoricalReportForm");
    var year = form.elements[0].value;
    var latitude = form.elements[1].value;
    var longitude = form.elements[2].value;
    var ppm_type = form.elements[3].value;

$.ajax({
  type: 'POST',
  dataType: 'html',
  url: '/api/historicalGraph',
  data: { latitude: latitude, longitude: longitude, year: year, ppm_type: ppm_type}, 
  success: function (data) {
    alert("The historical report will be displayed!");
  },
  error: function (data) {
    alert("Something went wrong, please try again later!");
  }
});

This is the code in queries.js

app.post('/api/historicalGraph', function(request, response, next) {
const data = {
  year: request.body.year,
  latitude: request.body.latitude,
  longitude: request.body.longitude,
  ppm_type: request.body.ppm_type
};

response.render('pages/historicalReportGraph', {
  year: data.year,
  latitude: data.latitude,
  longitude: data.longitude,
  ppm_type: data.ppm_type,
  email: request.user.email,
  privilege: request.user.privilege
});

});



via Veronica

AWS S3 Image Uploader with NodeJS and s3-uploader module

I am trying to use this module https://www.npmjs.com/package/s3-uploader but for me it's not clear how to implement it. How to do a POST to my router ?

.post('/upload', ensureAuthenticated, (req, res, next) => {

}

Does anybody is using this NodeJS module? Please I need help to understand it. Thank you so much

I found a related but not fully helpful topic in this thread: Node.js S3-uploader issue



via Matt

Converting nodejs cipher code to java

So I have this decryption code snipped from nodejs and I'm trying to convert that to java with no success, can someone help me with it?

var cipher = crypto.createDecipheriv('bf-cbc', key, new Buffer([0, 1, 2, 3, 4, 5, 6, 7])); cipher.setAutoPadding(false); bytes = cipher.update(bytes, 'binary', 'binary') + cipher.final();



via Revo

Cannot get property from the object retrieved by find query in Mongoose

I want to retrieve user data from mongodb, except userpw. so I select email propert only. When I send response as res.json(user) it prints the object well. but it fails, response shows undefined when I use user.email instead.

here is query I called:

User.findOne({username: req.params.username}, {email: 1}, (err, user) => {
       if (err) {
           console.log(err.stack);
           return;
       }
       console.log(user.email, typeof user);
       res.send(user.email);
});

Here is my userSchema:

const userSchema = new Schema({
    username: String,
    email: String,
    userpw: String
});

Here is my data on MongoDB:

> db.users.insert({username: "kkr", email: "kidkkr@naver.com", userpw: "aabb"})
WriteResult({ "nInserted" : 1 })
> db.users.find()
{ "_id" : ObjectId("58e99299d3e4e1768eb68cda"), "username" : "kkr", "email" : "kidkkr@naver.com", "userpw" : "aabb" }



via kidkkr

Deploy MeteorJs app to Google App Engine

I've been trying to deploy a Meteor 1.4.3.2 app to Google App Engine To no avail.

I've tried the following instructions -

All of which leave me with the same result - Error: Can't find npm module 'meteor-deque'

if I install the package manually in programs/server and try to deploy again I get - Error: Can't find npm module 'mongodb'

So I install mongodb manually and finally get Error: Cannot find module './entry.js'

Is there any one out there that has successfully deployed a meteor 1.4.3.2 app on Google Ap Engine that can help me out?



via vacarsu

Error Login Mongoose and Bcrypt

I am having an issue trying to log using mongoose and bcrypt. I get the error:

TypeError: cb is not a function

My model:

const mongoose = require('mongoose');
const Schema =  mongoose.Schema;
const bcrypt = require('bcrypt');
SALT_WORK_FACTOR = 10;

const userSchema = Schema({
  email:{type: String, required: true},
  encrypted_password:{type: String},
  active:{type: Boolean},
  role_id:{ type: Schema.Types.ObjectId, ref: 'roles' ,required: true},
  create_date:{type: Date, default: Date.now},
});

userSchema.methods.comparePassword = function comparePassword(candidatePassword, cb) {
  bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {
    if (err) {
      return cb(err);
    }

    cb(null, isMatch);
  });
};

const User = module.exports = mongoose.model('users',userSchema);

My authentication method:

const express = require('express')
  , router = express.Router()
const app = express();
const jwt = require('jsonwebtoken');
app.set('superSecret', 'XXXXXXX');

Users = require('./../database/models/people_culture/user');

module.exports = function(app){

app.post('/api/authenticate', (req, res) => {
  Users.findOne({email: req.body.email}, function(err, user) {
    console.log(user)
    if (err) throw err;

    if (!user) {
      res.json({ success: false, message: 'Authentication failed. User not found.' });
    } else if (user) {
password.' });
      var ismatch = user.comparePassword(req.body.password);
      if(!ismatch){
        res.json({ success: false, message: 'Authentication failed. Wrong password.' });

      } else {

        var token = jwt.sign(user, app.get('superSecret'), {
          expiresIn: 1440 // expires in 24 hours
        });

        res.json({
          success: true,
          message: 'This is the key',
          token: token
        });
      }

    }

  });
});

app.use('/api', router);
}

I follow several tutorials and always get the same error. The function to hash the password works fine, but when I try to compare the password can't log in because of this error.

I am using Express, Mongoose, JsonWebToken and bcrypt to authenticate the user.

Thanks in advance



via joselegit

how to run a python script from node js

i have written a server in nodejs on raaspberry pi. iwant to run a python script from it but it does not execute the line . on previous instances i have run files but comming this instance of socket.io i cant run the file!!though the console shows accurate output passed to it from the client .but it fails to read the file. the socket responsible for movement . `/*jshint esversion: 6 */

var express = require('express');
// library for executing system calls
const spawn = require('child_process').spawn;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
app = express();
server = require('http').createServer(app);
io = require('socket.io').listen(server);
var colour = require('colors');
var ip = require('ip');

var PortNumber = 3000;

var xPos = 0, yPos = 0;

server.listen(PortNumber);
app.use(express.static('public'));


io.sockets.on('connection', function (socket) {

    socket.emit('ip', {value: 'http://' + ip.address() + ':8081'});

    // otp generation socket
    socket.on('userEmail', function (data) {
        var userEmail = data.value;

        // system call to generate OTP
        const OTPgeneration = spawn('python', [__dirname + '/python/OTPgeneration.py', userEmail]);
        OTPgeneration.stdout.on('data', (data) => {
            console.log(`${data}`);
        });
    });

    // otp submit button socket
    socket.on('userOtp', function (data) {
        var userOtp = data.value;
        console.log(userOtp);

        // system call to generate OTP
        const otpValidate = spawn('python', [__dirname + '/python/OTPvalidation.py', userOtp]);
        otpValidate.stdout.on('data', (data) => {
            console.log(`${data}`);

            // Get last output from python file
            var lastChar = `${data}`.slice(-2);

            if (lastChar === '0\n') {
                console.log('Wrong OTP');
            }
            else io.sockets.emit('otpConformation', {value: 'confirm'}); //sends the confirmation to all connected clients
        });
    });

    // x y values socket
    socket.on('servoPosition', function (data) {
        servoPosition = data.value;
        // servoPosition[0] is x and servoPosition[1] is y
        console.log('Reveived X: ' + servoPosition[0] + '  Y: ' + servoPosition[1]);
        // system call for i2c comminication
        const i2cData = spawn('python', [__dirname + '/python/sendI2C.py', servoPosition[0], servoPosition[1]]);
        i2cData.stdout.on('data', (data) => {
            console.log(`${data}`);
        });
    });

    // movement socket
    socket.on('movement', function (data) {
        var m = data.value;
            console.log("Movement :" + m);
  const submitMove = spawn('python', [__dirname + '/python/move.py', m]);
        submitMove.stdout.on('data', (data) => {
            console.log(`${data}`);
        });

    });
});

console.log('Server Running @'.green + ip.address().green + ":3000".green);

function readTextFile(file) {
    var rawFile = new XMLHttpRequest();
    //var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
        if(rawFile.readyState === 4) {
            if(rawFile.status === 200 || rawFile.status === 0) {
                allText = rawFile.responseText;
                //alert(allText);
            }
        }
    };
    rawFile.send(null);
}
`



via pradumna

Node application runs on Heroku but not localhost

I have a simple REST API using MEAN. It's hosted on Heroku, and everything works well there. However, if I try to run it on localhost I get the following error:

TypeError: Parameter "url" must be a string, not undefined
at Url.parse (url.js:81:11)
at Object.urlParse [as parse] (url.js:75:5)
at module.exports (/Users/ricardotaboada/Desktop/sbackend/node_modules/mongodb/lib/url_parser.js:15:23)
at connect (/Users/ricardotaboada/Desktop/sbackend/node_modules/mongodb/lib/mongo_client.js:403:16)
at Function.MongoClient.connect (/Users/ricardotaboada/Desktop/sbackend/node_modules/mongodb/lib/mongo_client.js:227:3)
at Object.<anonymous> (/Users/ricardotaboada/Desktop/sbackend/server.js:15:21)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)

Any idea what's going on? Thanks very much.



via R. Taboada

node.js with mongodb and angularjs data binding

I'm trying to receive data from node.js with angularjs.

without angularjs, I can handle mongodb data but with angularjs, I cannot handle it.

when alerting data received from node.js, it shows [object object].

but on jade, no data showing now.

app.get and angularjs works fine but no data binding.

any ideas for me?

thank you for reading!

app.js

app.get('/studentlist', (req, res) => {    
    dbs.collection('slist').find({}).toArray((err, result) => {
        if (err) return console.log(err)
        //res.send(JSON.stringify(result));  
        var data = JSON.stringify(result);
        //console.log(data);
        res.send({ result: data });
        console.log('data sent');
    });   
});

angular.js code

var app = angular.module("datalist", []);
app.controller('datadisplay', function ($scope, $http) 
    var vm = this;
    vm.mydata = [];
        $http.get('/studentlist').then(function (result) {
            alert(result.data);
            $scope.slist = result.data;
        })

});

jade code

extends layout

block content
    h1 Student list    
    label Search:
        input(ng-model="searchText")
    .studentlist 
        table.table
            thead
                tr
                    th Name
                    th Age
                    th Class                    
            tbody(ng-app="datalist")             
                    tr(ng-controller="datadisplay" ng-repeat"mongo_result in slist | filter:searchText")
                        form(action='/detail', method="POST" class="slist")
                            th
                                
                            th
                                
                            th
                                
                            th
                                button.btn-primary(type="submit") Detail
                            th 
                                button.btn-danger(type="button" class="btnOrderLiterature" data-value="" value="" ng-click="addLiteratureToSession($event)") Delete



via Chi Seong Oh

Signalmaster on https: ERR_CONNECTION_REFUSED

I have an ember project using Signalmaster. In the config/environment.js I have the following:

if (environment === 'production') {

ENV.SIGNALMASTER = {
  HOST: 'https://localhost:8890',
  PORT: '8890',
  FORCE_CONNECTION: true
};

On my server I have signalmaster running at https://localhost:8890 (in the development.json and production.json files in the config directory for signalmaster I have secure set to true, and in the server.js file for signalmaster I've put in the location of my SSL certificate and key, as is required for running it on https) - when running "node server.js" I get the following:

signal master is running at: https://localhost:8890

Running "netstat -lnp" also shows a process running on port 8890. However when I use the app I get errors like this:

GET https://localhost:8890/socket.io/?EIO=3&transport=polling&t=LjG8--J net::ERR_CONNECTION_REFUSED

I am using socket.io version 1.3.7.



via ZhouW

nodejs child_process only get empty

when i use child_process exec/spawn for cmd

  • git gc
  • git fsck --full

will only get '' for stdout/stderr

but it should return

$ git gc
Counting objects: 284, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (99/99), done.
Writing objects: 100% (284/284), done.
Total 284 (delta 169), reused 284 (delta 169)

$ git fsck --full
Checking object directories: 100% (256/256), done.
Checking objects: 100% (284/284), done.

what is wrong here how do i get it



via bluelovers

NextJS + ExpressJS Error with On Demand Entries Ping

I'm using NextJS and custom server with Express, But I got a problem when defining my routes in Express.

When I define Express routes like below it will throw an errors

app.get('/:username', handle.profile)
app.get('/:username/:id', (req, res) => {
  res.send('id')
})

But the errors just appears when I'm in Development mode. Which is when I go with Production the errors not shown.

Though errors in console, but all run normally, I just can't figure out why the error message coming. It's a weird.

Here's the errors message

Error with on-demand-entries-ping: Unexpected token i in JSON at position 0

Here's screenshot of the errors Express routes error

But when I define Express routes like below

app.get('/:username', handle.profile)
app.get('/:username/forum/:id', (req, res) => {
  res.send('id')
})

In Production or Development mode the errors is go on, my application going well.

Any solution please?



via Habib Rohman

How to implement autocomplete search movie name in telegram bot

  • I am using NODEJS at backend to fetch movie data from IMDB NPM api.Following is my server.js code.

    server.js

    var token ="token"; var telegramBot= require('node-telegram-bot-api'); var bot= new telegramBot(token,{polling:true}); var express= require('express'); var imdb = require('imdb-api');

    var app =express();

    app.listen(8080,function(){ console.log("listening on 8080") })

    bot.onText(/Moviename/, function(msg, match) { data = msg.text; imdb.get(msg.text, function(err, movieList){ console.log(movieList); bot.sendMessage(msg.chat.id,movieList); //how i send data to bot when I type on keyboard

    }); });



via Harishchandra chincholkar

Authenticate static assets (HTML) with Angular 2 using NodeJS as API?

I created an API that returns data using NodeJS; this runs on port 3000. I then created a Angular 2 project using angular-cli. This is running on port 4200.

All is well until I thought about authentication. I am not sure how I can authenticate pages that are served up through the lite-server that Angular2 uses. I have really enjoyed the separation of concerns as I don't have to deal with the views with NodeJS.

How am I able to authenticate the server that comes built into a angular-cli build that would allow more too reject pages if user is not authenticated?



via Phil

Returning The Right API Information (Zendesk, Botkit)

I'm building a bot through botkit and it is using Zendesk api to pull information.

I have a function that asks a user for a search term and the bot searches relevant information about that search term. It pulls the information from the Zendesk API and outputs the answer.

My problem is when the user types the search term 'Jim', it will work correctly and pull back information from the tickets[0] element.

However, when a user types in a word like 'bank', it will not work. 'Bank' would have 2 elements within the array- tickets[0], tickets[1]. I understand that I'm only asking the first element of the array to be outputted, but why does it not output anything when theres more than one element within the tickets array?

Here is the code:

controller.hears(['SEARCH TICKET',/search ticket/gi,  /^.{0,}jirabot.{0,}$/],
['direct_message','direct_mention','mention','ambient'],function(bot,message) {

 // start a conversation to handle this response.
 bot.startConversation(message,function(err,convo) {

convo.ask('What are you looking for?',function(response,convo) {

  zendesk.search.list('query='+response.text+'&sort_by=priority&sort_order=desc').then(function(tickets){
console.log(tickets);
bot.reply(message, 'The Ticket ID Number: ' + tickets[0].id + '\n The Ticket Priority: ' + tickets[0].priority + '\n The Ticket Subject: ' + tickets[0].subject + '\n The Ticket Description: \n'+ tickets[0].description + '\n');
convo.next();
});

 });

});

});

Here is a link to the botkit documentation: https://github.com/howdyai/botkit

Here is a link to the zendesk API documentation: https://developer.zendesk.com/rest_api/docs/core/tickets#list-tickets



via Writer316

Post to google+ wall from plusDomains api

I'm trying to post to my google+ wall from the api. I have gone through and granted the correct OAuth scopes and appropriately enabled the plusDomains Api on my console but I am still getting a 403 error.

                    var google = require('googleapis')
                    var auth = new google.auth.OAuth2();

                    auth.setCredentials({
                        access_token: accessToken
                    });
                    google.plusDomains('v1').activities.insert({
                        userId: 'me',
                        body : {
                             'object' : {
                                 'originalContent' : 'foo'
                             },
                             'access' : {
                                 'items' : [{
                                     'type' : 'domain'
                                 }],
                                 'domainRestricted': "true"
                             }
                     },
                         auth: auth
                     }, function (err, response) {
                     if (err) {
                         console.error(err)
                         res.send(err.code, err)
                     } else {
                         console.log(response)
                         res.send(200)
                     }
                     });



via immexerxez

Retrieve Cookie, store, and use

I'm using npm package 'request' to make API calls. Upon initial login, I should receive a cookie back, I need to store that cookie indefinitely to make subsequent calls.

I'm doing this in Python with requests like so:

#set up the session   
s = requests.session()
#logs in and stores the cookie in session to be used in future calls
request = s.post(url, data)

How do I accomplish this in node? I'm not tied to anything right now, the request package seems easy to work with, except I'm having issues getting known username and passwords to work, that said, I'm sure that's mostly my inexperience with JS/node.js.

This is all backend code, no browsers involved.

I need to essentially run a logon function, store the returned encrypted cookie and use for all subsequent calls against that API. These calls can have any number of parameters so I'm not sure a callback in the logon function would be a good answer, but am toying with that, although that would defeat the purpose of 'logon once, get encrypted cookie, make calls'.

Any advice, direction appreciated on this, but really in need of a way to get the cookie data retrieved/stored for future use.



via Dr. Nefario

Node.js: Long-polling with EventEmitter and Express 4.x | Catching request close

I'm long-polling node.js route with JQuery's ajax request (xhr). This sends a GET request to my Express server and listens for message bus events. I'm setting a timeout on that GET request (as my proxy would kill long requests). So after the timeout, an abort event should be sent by the client to the server.

I want to catch that abort/close/finish event and remove the relevant message bus listener/subscriber.

But I struggle. I tried req.on("close"..) and the on-finished npm module, but that didn't work for me. I'm also not much more clever after reading the http documentation of node: https://nodejs.org/api/http.html.

Any ideas how to tackle this beast? Or better ways to remove listeners to prevent memory leaks?

Server side essentials:

// server.js
var express = require("express");
var EventEmitter = require("events").EventEmitter;
var messageBus = new EventEmitter();
messageBus.setMaxListeners(20);

var REST_PORT = (process.env.PORT || 5000);
var app = express();

app.get("/events", (req, res) => {
    var listener = function(res) {
        messageBus.once("message", function(data) {
            res.status(200).json(data);
        });
    };
    req.on("abort", function() { //I tried also "aborted", "close", "closed", "finish", "finished"..no luck
        messageBus.removeListener("message", listener);
    });

    listener(res);
    console.log("Total listeners to 'message' events:", messageBus.listeners("message").length);
});

// other messageBus.emit logic ..

app.listen(REST_PORT, () => {
    console.log("Application ready on port " + REST_PORT);
});

Client side essentials:

//client.js
$.ajax({
    method: "GET",
    async: true,
    url: "/events",
    success: function(data) {
        callback(data);
    },
    complete: function(request, status, err) {
        if (status == "timeout" || status == "success") {
            console.log("LOG: Normal long-polling timeout or successful poll, continuing.");
            longPoll();
        } else {
            console.warn("WARN: Server probably offline, retrying in 2 sec.");
            setTimeout(function() {
                longPoll();
            }, 2000);
        }
    },
    timeout: 30000
});

Thank you!



via flaesh

Connect to a heroku server with socket.io

How would one go about connecting to a heroku node.js server? For example, I have a server named 'https://example.herokuapp.com/' that uses node.js. How would I connect to it from a normal javascript file running socket.io. The code might look something like this:

var socket = io();
socket.connect('https://example.herokuapp.com/', { autoConnect: true});

I have tried this and I get the output of

polling-xhr.js:261 GET http://file/socket.io/?EIO=3&transport=polling&t=LjFlRl1 net::ERR_NAME_NOT_RESOLVED

So would I need an IP for the heroku server? If so how do I get it and is it even possible with heroku. If you're wondering why I don't host the html file on heroku it's because I'm using it for a website and my web host doesn't support node.js hosting. So I decided to host the node.js server on heroku. Thanks for your help in advance.



via McMatt

Write EXIF data to image stream Node.js

I found a nice npm package that allows you to read and write Exif data to images, https://github.com/Sobesednik/node-exiftool.

The challenge that I have is that it requires you to provide the path to an image. So, the image has to be written to disk if you want to modify the EXIF using this package. Is there an easy way to check/read the EXIF, and if necessary, write EXIF data to an image stream?

var imageURL = 'https://nodejs.org/static/images/logos/nodejs-new-pantone-black.png'
var upstreamServer = 'http://someupstreamserver/uploads'

request
  .get(sourceUrl)
  .pipe(
      // TODO read EXIF
      // TODO write missing EXIF
      request
        .post(upstreamServer, function(err, httpResponse, body){
          res.send(201)
      })
  )



via tom

Search in a reference text field with Mongoose

I have this Schema

var users = new Schema({
    name: {type: String, required: true},
    email: {type: String, required: true},
    password: {type: String, required: true},
    following: [{type: Schema.ObjectId, ref: "users"}]
});
users.index({name: 'text'});

I want to use Mongoose to find users who they have "john" in their name and they are exists in following array of user of _id = x

in other way if it was SQL the query would be (it just example to illustrate the relations)

SELECT * FROM users where _id = x AND users.following.name LIKE '%john%'

I think that if following array was embedded in the user collections it would be easy to make.

How can i handle that in mongoose ?



via Moustafa Elkady

Having trouble writting remotely to Cassandra server from node.js

Environment: OS: Debian, Cassandra: 3.10, Node.js 7.5.0,cassandra-driver: 3.2.0

Error: (node:7484) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: All host(s) tried for query failed. First host tried, 192.168.10.151:9042: Error: connect ECONNREFUSED 192.168.10.151:9042. See innerErrors.(node:7484) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Nodejs Code:

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var fs = require('fs');
var cassandra = require('cassandra-driver');
var async = require('async');
var client = new cassandra.Client({contactPoints: ['192.168.10.151'], keyspace: 'users'});

router.post('/', function(req, res, next) {
    var query = 'INSERT INTO userAuth(email,password) VALUES(req.body.email,req.body.password)';
    client.execute(query);
    });

module.exports = router;

I am not sure what i am doing wrong.



via Iwin

Eslint expected indentation of 1 tab but found 4 spaces error

I am using VScode with latest version of Eslint. It is my first time using a linter.

I keep getting this linting error when using a tab as indentation:

severity: 'Error' message: 'Expected indentation of 1 tab but found 4 spaces. (indent)' at: '4,5' source: 'eslint'

Here is my config file

{
"env": {
    "browser": true,
    "commonjs": true,
    "es6": true,
    "node": true
},
"extends": "eslint:recommended",
"rules": {
    "indent": [
        "error",
        "tab"
    ],
    "linebreak-style": [
        "error",
        "unix"
    ],
    "quotes": [
        "error",
        "single"
    ],
    "semi": [
        "error",
        "always"
    ]
}
}

I don't understand why this error is being thrown as I indicated tabs for indentation. It is obviously calculating my 1 tab as 4 spaced but I don't understand why it is doing that when I am pressing tab for indentation.

Thanks



via JohnSnow

Socket io private messages using expressjs nodejs mongoose

hello guys so i'm strugling with socket.io i'm trying to make a chat between my users that are logged in in my app , so i followed the begginner cours about socket.io and i could make a private chat app but the users aren't the ones that are in my database or they have to create a username to connect to the chat app and so... in my search i found this one he's making a chat app using laravel

i want the exact same app but using nodejs mongoose express. can you hlep me with some references or tutorials thank you very much



via ghaieb sahbi

ar-drone Cannot read property 'latitude' of undefined intermittent data

When I use this code I see error messages, then gps data then back to error messages. Can anyone tell me why this happens?

var arDrone = require('ar-drone');
var droneClient = arDrone.createClient();
droneClient.config('general:navdata_demo', 'FALSE'); // get back all data the copter can send
droneClient.config('general:navdata_options', 777060865); // turn on GPS

droneClient.on('navdata', function(navdata) {

  try {
    console.log(navdata.gps.latitude + ', ' + navdata.gps.longitude);
}
catch(err) {
    console.log(err.message);
}


});

Here is what I see when I execute this. It seems the gps data never comes back.

Cannot read property 'latitude' of undefined 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 43.6330829, -116.4467156 Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined Cannot read property 'latitude' of undefined



via Kevin Hunkovic

Pass data from Flask(python) backend to Nodejs frontend

Situation is next:

Backend - Flask(python)

Fronted - nodejs(+webpack). Webpack compiling all js's to 1 file(dashboard.js). As result - all js code is totally frontend which executing at moment when html page loading.

Details: application deploying and executing on remote host. I have a config file(json) which stored on remote host. And I need to pass data from it to js code.

Goal - set variable in js according to backend variable.

My attemts:

  • I tryed to parse it by fs - error that fs is not found. I guess because fs is plugin for backend-oriented tasks and not for browser(if I'm wrong - please let me know)
  • Tried to import file in js - obviously webpack precompiling file from my local disk and not reading it on remote host
  • tried to create one more route(like /route) to return needed value from backend. Almost good but here is main problem - request took some time and when request(with response) done page already loaded.
  • tried to pass data into html template(like ) - to parse it by js - but document.body available after page loaded

    Which would be a good solution for this situation? Need to have this variable availbale at moment when js classes start to initializing

If question is not correct or some details missing - my appologies(please let me know)



via Eugene

'moment is not defined' error - due to upgrade to node v6.10.2?

I recently upgrade my node..js function to v6.10.2 and suddenly my use of 'moment' has stopped working and I get the above error. I have not changed the code in the file that is throwing the error at all. Code snippet is:

                <div class="col-md-4 date">
                     <%= moment(comment.created).fromNow()%>
                </div>

And I require moment in both my app.js and my route file which accesses this page as follow:

moment                  =       require("moment"),

Is this a version issue?



via DaveB1

Exposing Endpoints in OpenShift Online Node/Express Applications

I have an OpenShift Online application built using the Node.js cartridge. My application defines express routes in its server.js file (I just updated the default Node.js cartridge server.js file):

self.routes['/path'] = function(req, res) {
    // code
}

I'm trying to determine how to expose these endpoints in the deployed application. Currently I get 503 errors when I try to access my endpoints (http://app-user.rhcloud.com/path). My application works fine when I'm running it locally, so the issue is unique to the version deployed by OpenShift.

I believe I need to add the endpoints to my manifest.yml file but I'm not sure of the correct way to do this. Even directly editing the file (which does not seem correct) is impossible because it is read-only protected. The only documentation I've found seems to be specific to creating your own cartridges or to OpenShift Enterprise applications. Any help would be appreciated.

Thanks,

Thomas



via Thomas Schellenberg

Nothing is being shown while there's no error. The code is working fine

app.js

angular.module('app', ['ionic', 'ui.router'])

.config(('$urlRouterProvider', '$stateProvider', function($urlRouterProvider,$stateProvider){
    $urlRouterProvider.otherwise('/');
    $stateProvider
    .state('view',{
      url:'/',
      templateUrl:'js/components/view/view32.html',
      controller:'viewCtrl'
    })

}))

server.js

 var express= require('express');
var mongoose = require('mongoose');
var bodyParser=require('body-parser');
var cors= require('cors');
var app= express();
var multiparty= require('connect-multiparty');
var multipartMiddleware= multiparty();
var viewController=require('./controllers/viewController');
var shareController=require('./controllers/shareController');
var configs = require('./configs/config.js');
configs.setConfigs();

mongoose.connect(process.env.MONGO_URL);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(multipartMiddleware);
app.use(cors());

app.use('/app', express.static(__dirname+ '/app'));
app.get('/',function(req,res){
    res.sendFile(__dirname +'/index.html');
});
app.post('/share', multipartMiddleware, shareController.shareNewPicture);
app.get('/getNewPhoto', viewController.getNewPhoto);
/*app.use(function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header('Access-Control-Allow-Methods','POST, GET, OPTIONS, PUT');
next();
});*/
var port = 8080 || process.env.PORT;
app.listen(port, function(){
    console.log('Server Started '+ port);
});

view.js

 (function(window, angular, undefined)
{
    angular.module('app')
    .controller('viewCtrl',['$scope','$state','$http',function($scope,$state,$http)
    {   
        $scope.pics=[];
        $http.get('http://localhost:8080/getNewPhoto').then(function(response){
            $scope.pics=response.data;
            console.log('Hello photos are here');
        },function(err)
        {
            console.error("There's an error"+err);
        })
    }])
})(window,window.angular)

The index.html where I'm calling views index.html

    <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>
    <link rel="manifest" href="manifest.json">
    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <script src="lib/ionic/js/ionic.bundle.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.min.js"></script>
    <script src="cordova.js"></script>
    <script src="js/app.js"></script>
    <script src="js/components/view/view.js"></script>
  </head>
  <body ng-app="app">

    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title"></h1>
      </ion-header-bar>
      <ion-content>
        <div ui-view>
        </div>
      </ion-content>
    </ion-pane>
  </body>
</html>

Here's the view.html which i want to show view1.html

<div>
    <div ng-repeat='pics in pic'>
        <p> This is the view.html</p>
        <img ng-src=/>
    </div>
</div>

There's nothing happening with view. I'm trying to get the view of photos but its not showing any error or any view. Please if anybody could help!!



via Asad Arshad

Java start Node.js program immediately closes

I'm trying to make a Discord bot that has a Java FXML interface along with a Node.js program to make for an Audio playing bot.

When I try to open the process for Node.js inside Java I'm noticing that it instantly closes because when I try to write I get the IOException pipes are being closed. I am unsure why this happens because when I run node inside the command line the exact same way it stays open. Does anyone know why my process immediately closes?

Node.js communication class:

public class NodeCommunicationHandler {

private static final Logger LOG = Logger.getLogger(NodeCommunicationHandler.class.getName());

private Process nodeProcess;
private ExecutorService threadPool;
private ProcessHandlerTask callbackHandler;
private StringProperty callback;
private OutputStream writeStream;

/**
 *
 */
public NodeCommunicationHandler() {
    try {
        // Activate Node.js sub-process
        this.nodeProcess = new ProcessBuilder("cmd", "/c", "start", "node", "\"" + Reference.NODE_PROGRAM_LOCATION + "\"").start();

        // Initialize the stdout writing stream
        this.writeStream = this.nodeProcess.getOutputStream();

        // Initialize the stdin reader on the process
        this.callbackHandler = new ProcessHandlerTask(this.nodeProcess);

        // Bind the callback data from the process to the callback property
        this.callback = new SimpleStringProperty();
        this.callback.bind(this.callbackHandler.messageProperty());

        // Run the thread of the process callback handler
        this.threadPool = Executors.newFixedThreadPool(2);
        this.threadPool.submit(this.callbackHandler);
    } catch (IOException ex) {
        NodeCommunicationHandler.LOG.log(Level.SEVERE, null, ex);
    }
}

/**
 * Retrieve the internal process callback.
 *
 * @return The callback.
 */
public StringProperty getCallback() {
    return this.callback;
}

/**
 * Writes a string command to the Node.js process.
 *
 * @param command The command to write.
 */
public void write(String command) {
    try {
        this.writeStream.write(command.getBytes());
        this.writeStream.flush();
    } catch (IOException ex) {
        NodeCommunicationHandler.LOG.log(Level.SEVERE, null, ex);
    }
}

/**
 * Stop the Node.js process
 */
public void stop() {
    try {
        // Write the command STOP towards the node process to promptly exit the discord API.
        this.write("STOP");

        // Close the writing stream since STOP is the last command we have to write.
        this.writeStream.close();

        // Wait for the Node.js acknowledgement of the STOP issue.
        NodeProcessExitHandler exitCond = new NodeProcessExitHandler(this.callback);
        this.threadPool.submit(exitCond).get();

        // Unbind the callback listener.
        this.callback.unbind();

        // Stop the callback handler and let the thread finish.
        this.callbackHandler.stop();

        // Keep the process alive until the callback handler has been disconnected.
        this.threadPool.awaitTermination(10000, TimeUnit.MILLISECONDS);

        // Kill the subprocess since we know
        this.nodeProcess.destroy();
    } catch (IOException | InterruptedException | ExecutionException ex) {
        NodeCommunicationHandler.LOG.log(Level.SEVERE, null, ex);
    }
}
}

And my javascript program:

var stdin = process.openStdin();

stdin.addListener("data", function(d) {
    console.log("You entered: " + d.toString());
});

The javascript is really basic but it should be able to provide what I need.



via Thodor12

System.Exception: Call to Node module failed with error: Error: URLs requested via Http on the server must be absolute

System.Exception: Call to Node module failed with error: Error: URLs requested via Http on the server must be absolute. URL: /Account/GetUser/

This error happens when calling http from Angular Universal. From the server, I have no access to the 'location' object.

Why is there a restriction in Angular preventing calling web services from a relative url?

How can I retrieve the host name without using 'location'?



via Jonas Arcangel

Wrapper around browserify require?

I have a server in NodeJS and a heavy JS front end.

The server and the client share a lot of the same code but right now I'm requiring them with relative paths.

I looked up all the different methods of overcoming this problem and I really like the idea of creating a global custom require method that wraps around the built in require method. So now for example I can call "MyRequireFunction()" instead of "require()" and it works the same way.

This works great in NodeJS, but now I'm trying to figure out how to do it for the client too. Because they share the same code I want it to run the same function ("MyRequireFunction()").

I don't want if statements that check if it's node or the browser. I'm looking for a clean solution where I can require a file without a relative path on a single line that works on both platforms. The custom require method is perfect for this, I'm just not sure how to go about doing it on the client using browserify and gulp.

If I wrap require in a custom javascript function it doesn't treat it the way it's supposed to because I guess it thinks the function is part of the code, so how do I go about solving this in the way I'm looking for?



via user1157885

Error with query sending Unhandled rejection SequelizeConnectionError: read ECONNRESET

PostgreSQL 9.6.2 windows 10 x64. I send query from node.js application.

Controller

authorize(req).then(function (foundUser) {
  //get data from db and send it for client
}), function (err) {
  res.status(200).send('User not found');
}

authorize.js

module.exports = function (req) {
  var decodeToken = jwt.decode(req.cookies.token, JwtOptions.secretOrKey);
  return db.users.findById(decodeToken.id)
    .then(function (foundUser) {
      return foundUser;
  }).catch(function (err) {
    //get here the exception
    return err;
  });
}

Sometimes I get data from db and sometimes get an error:

Unhandled rejection SequelizeConnectionError: read ECONNRESET
    at D:\NodeJSProjects\ParkingHouse\node_modules\sequelize\lib\dialects\postgres\connection-manager.js:110:20
    at Connection.<anonymous> (D:\NodeJSProjects\ParkingHouse\node_modules\pg\lib\client.js:186:5)
    at emitOne (events.js:96:13)
    at Connection.emit (events.js:188:7)
    at Socket.<anonymous> (D:\NodeJSProjects\ParkingHouse\node_modules\pg\lib\connection.js:86:10)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at emitErrorNT (net.js:1278:8)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)

and after some time get result from db

db logs has errors:

2017-04-08 23:13:04 EEST —:  could not reserve shared memory region (addr=00000000022D0000) for child 00000000000016B0: error code 487
2017-04-08 23:13:04 EEST —:  could not fork autovacuum worker process: No error

How to solve this problem?



via Sergei R

Why can't I POST /login with Node and Passport?

I am setting up Passport with Node/Express app (with MongoDB). For some reason I am unable to POST to /login. Strangely, the BasicStrategy instance I've set up isn't even running at all.

When I run it in Postman, I get the html file back. When I try it in the browser, for some reason I get a 200 response with the failureRedirect.

The strangest thing is that the strategy is not being called at all; the terminal console doesn't log any of the console.logs that I have set up whatsoever.

Any help would be highly appreciated. Thank you.

Here is my login router:

/users/routes/loginRouter.js

const {BasicStrategy} = require('passport-http'),
      express = require('express'),
      jsonParser = require('body-parser').json(),
      passport = require('passport');

const {User} = require('../models');

const loginRouter = express.Router();

loginRouter.use(jsonParser);

const strategy = new BasicStrategy(function(username, password, callback) {
  console.log(arguments);
  let user;
  User
    .findOne({username: username})
    .exec()
    .then(_user => {
      console.log(_user);
      user = _user;
      if (!user) {
        return callback(null, false, {message: 'Incorrect username'});
      }
      return user.validatePassword(password);
    })
    .then(isValid => {
      console.log(isValid);
      if (!isValid) {
        return callback(null, false, {messsage: 'Incorrect password'});
      }
      else {
        return callback(null, user)
      }
    });
});

passport.use(strategy);
loginRouter.use(passport.initialize());

loginRouter.post('/',
  passport.authenticate('basic',
    {
      session: true,
      successRedirect: '/console',
      failureRedirect: '/login'
    }
  )
);

module.exports = {loginRouter};

Now this is my server file:

/server.js

const express = require('express'),
      bodyParser = require('body-parser'),
      mongoose = require('mongoose'),
      passport = require('passport');

const {adminRouter} = require('./users/routes/adminRouter'),
      {loginRouter} = require('./users/routes/loginRouter'),
      {registerRouter} = require('./users/routes/registerRouter'),
      {PORT, DATABASE_URL} = require('./config'),
      {router} = require('./router');


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

mongoose.Promise = global.Promise;

app.use(bodyParser.json());

app.use(express.static('public'));

app.use(passport.initialize());
app.use(passport.session());

app.use('/api/users/', registerRouter);
app.use('/login', loginRouter);
app.use('/console', adminRouter);

app.use('/', router);

app.get(['/login', '/register', '/about', '/archive', '/maxim/:maximId', '/console'], (req, res) => {
  res.sendFile(path.resolve(__dirname, 'public', 'index.html'))});


function runServer(databaseUrl=DATABASE_URL, port=PORT) {

  return new Promise((resolve, reject) => {
    mongoose.connect(databaseUrl, err => {
      if (err) {
        return reject(err);
      }
      server = app.listen(port, () => {
        console.log(`Your app is listening on port ${port}`);
        resolve();
      })
      .on('error', err => {
        mongoose.disconnect();
        reject(err);
      });
    });
  });
}

function closeServer() {
  return mongoose.disconnect().then(() => {
     return new Promise((resolve, reject) => {
       console.log('Closing server');
       server.close(err => {
         if (err) {
           return reject(err);
         }
         resolve();
       });
     });
  });
}

if (require.main === module) {
  runServer().catch(err => console.error(err));
};

module.exports = {app, runServer, closeServer};

My other routes are working perfectly fine, for example this register route is functioning as expected:

/users/routes/registerRouter.js

const {BasicStrategy} = require('passport-http'),
      express = require('express'),
      jsonParser = require('body-parser').json(),
      passport = require('passport');

const {User} = require('../models');

const registerRouter = express.Router();

registerRouter.use(jsonParser);

const strategy = new BasicStrategy(
  (username, password, cb) => {
    User
      .findOne({username})
      .exec()
      .then(user => {
        if (!user) {
          return cb(null, false, {
            message: 'No such user'
          });
        }
        if (user.password !== password) {
          return cb(null, false, 'Incorrect password');
        }
        return cb(null, user);
      })
      .catch(err => cb(err))
});

passport.use(strategy);

registerRouter.post('/', (req, res) => {
  if (!req.body) {
    return res.status(400).json({message: 'No request body'});
  }

  if (!('username' in req.body)) {
    return res.status(422).json({message: 'No username in request body'});
  }

  let {username, password, email} = req.body;

  if (typeof username !== 'string') {
    return res.status(422).json({message: 'Incorrect field type: username'});
  }

  username = username.trim();

  if (username === '') {
    return res.status(422).json({message: 'Incorrect field length: username'});
  }

  if (!(password)) {
    return res.status(422).json({message: 'No password in request body'});
  }

  if (typeof password !== 'string') {
    return res.status(422).json({message: 'Incorrect field type: password'});
  }

  password = password.trim();

  if (password === '') {
    return res.status(422).json({message: 'Incorrect field length: password'});
  }

  if (typeof email !== 'string') {
    return res.status(422).json({message: 'Incorrect field type: email'});
  }

  email = email.trim();

  if (email === '') {
    return res.status(422).json({message: 'Incorrect field length: email'});
  }

  // check for existing user
  return User
    .find({username})
    .count()
    .exec()
    .then(count => {
      if (count > 0) {
        return res.status(422).json({message: 'Username taken'});
      }
      // if no existing user, hash password
      return User.hashPassword(password)
    })
    .then(hash => {
      return User
        .create({
          username: username,
          password: hash,
          email: email
        })
    })
    .then(user => {
      return res.status(201).json(user.apiRep());
    })
    .catch(err => {
      res.status(500).json({message: 'Internal Server Error'})
    });
});

module.exports = {registerRouter};



via Alacritas

Javascript: How to require using const

There's one thing I don't understand about modern Javascript. I see a lot of people discussing whether they should use var, const, or let when requiring new modules. Most people say it's const as their first priority and let second, but I don't see many people who are fan of var. However, this code down below would throw a error TS2451: Cannot redeclare block-scoped variable 'other' error. (Note: This error comes from the Typescript compiler, using the commonjs flag.)

main.js

'use strict';

const A = require('./A.js');
const B = require('./B.js');

// do more stuff

A.js

'use strict';
const other = require('./other.js');

class A {
    //...
};

module.exports = A;

B.js

'use strict';
const other = require('./other.js');

class B {
    //...
};

module.exports = B;

I'm not sure in which cases it's error-less to use const. It seems that it only works when a module is imported in the main module using const, and then everything else in other modules have var for importing the same module. I'd like to know if I'm missing something. Thanks.



via Felo Vilches

Uncaught ReferenceError: date is not defined | JavaScript NodeJs jQuery FileSystem

I was testing some stuff with javascript and nodejs. I wanted to ask the user a folder and it would show the name of the files in folder, the type of file (executable, text file...) and the changed date (when the file was changed or modified last time). The code below:

fs.stat(testFolder, (err, stats) => {
    var time = stats.ctime
    var day = time.getDay()
    var month = time.getMonth()
    var year = time.getFullYear()
    var date = day + " " + month + " " + year
})
const testFolder = './tests/'
const fs = require('fs')
fs.readdir(testFolder, (err, files) => {

    files.forEach(file => {
        var tmp = file.split(".")
        var name = tmp[0]
        var kind = kinds[tmp[1]]
        if(kind == null) {
            kind = "File"
        }
        $( "#test" ).append( "<tr class=\"file\">\
              <td>" + name + "</td>\
              <td>" + kind + "</td>\
              <td>" + date + "</td>\
            </tr>" );
    });
})

I have the variable time wich holds the full date. And when I use console.log(date) it works. console.log(date)

But when I try and add the date variable to the append method with jQuery it gives me an error: enter image description here



via ecoH

Tell me how can get data from html form to js file and to add mysql

 I have created two files index.html and main.js.Tell how I can get data from index.html file to main.js file and insert the in database.


     index.html

    // html form
        <form method="POST" action = "">

        <input type="text"  id="name" name ="name" placeholder="First Name">
        <input type="number"  id="age"  name="age" placeholder="Age">
                <select  id="gender"  name="gender">
            <option value = "male" >Male</option>
            <option value = "female">Female</option>
          </select>
                <input type="text"  id="phone"  name="phone" placeholder="Phone Number">
                <button type="submit" class="btn">Submit</button>

          </form>

        main.js //js file

I want to create a function whick send a index.html file on request and take data from that file and add to mysqldatabase. // creating connection to mysql databases var con = mysql.createConnection({ host:'localhost', user:'root', password:'1234', database:'project1' }); // checking connection con.connect(function(err){ if(err){ console.log('error connecting to database'); }else{ console.log('connected to databases'); } }); var publicPath = path.resolve(__dirname, '/');

       app.get('/', function(req, res) {
          res.sendFile(path.join('index.html',{root:publicPath}));
        });
        app.listen(5000, function() {
          console.log('Server running at http://127.0.0.1:5000/');
        });



via Suyog Pipliwal

How do I convert a JSON string into and an array of unknown objects?

I'm creating a simple flashcard generator and have a JSON String containing multiple arrays and objects that looks like this:

data = [{"front":"What is your name?","back":"Billy"},{"front":"How old are you?","back":"40"}][{"front":"Is this a test?","back":"yes"}]

When I console.log(data.length) i get 130.

I can enter more than one flashcard at a time, and can enter the flashcards at any given time. That's why there's the ][ are in the middle of it.

I'm trying to loop through said array and end up with something along the lines of:

data = [{"front":"What is your name?","back":"Billy"},{"front":"How old are you?","back":"40"},{"front":"Is this a test?","back":"yes"}]

Where console.log(data.length) = 3

And eventually data[i].front = "What is your name?"

Can someone please put me in the right direction? The data is being read from a txt file if that makes a difference.



via IsaacWIvins

Building PHP based web application using node.js for real-time notifications

It has been some time since i last developed something completely new so forgive me if this sounds like a stupid question.

I am now building a PHP based web application and from my experience i have always used ajax polling for notifications and stuff like that. From what i have understood Node.js is the way to go these days but i can't figure out how to implement these two.

Using:

  • MySQL for database
  • Nginx for web server
  • PHP as server-side programming

I want:

  • Different kind of real-time notifications sent to signed in users
  • Real-time chat between users

My goal here is to have PHP as the server-side language but some kind of system for the real-time notifications (probably using Node.js). Is this even possible, will it be optimal and how would i implement these two? Or is there any better way to achieve this when having PHP as the server-based language?

Thanks in advance for any examples/guides/information.



via user3604481

Using gulp instead of nodejs in IntelliJ ignores breakpoints

I have inherited a project running gulp+nodejs. I am trying to use IntelliJ in Windows as my IDE.

If I set my runtime configuration to use "node.js" as its type, I have no problem hitting breakpoints and debugging. However, if I use "gulp.js" as the run type, breakpoints are ignored (and I can essentially never debug). I also tried using Node.js configuration and setting the JS file to node_modules/gulp/bin/gulp.js instead of server/run.js . This seems to have the exact same problem.

Any thoughts on how I could fix this?



via Dakusan

merging two objects in nodejs using botkit

Hi guys i have a problem merging two objects any idea how can i do this ?

controller.hears('offres','message_received, facebook_postback',function(bot,message){

connection.connect("mongodb://localhost/bot",function(err,db){
    var z ="";
    var data = db.collection('offres').find().toArray().then(function(data){
        for (var i =0 ; i<10; i++){
            var _under = require("underscore");
            var titre = data[i]['titre'];
            var ref = data[i]['ref'].toString();
            var description = data[i]['description'];

            b = setpayload(titre,description, ref,'https://cdn.pixabay.com/photo/2017/01/13/17/29/hiring-1977803_960_720.jpg');
              z= _under.extend(z, b);
          }
        bot.reply(message,{
            attachment:{
            'type': 'template',
            'payload': {
                'template_type': 'generic',
                'elements':[z    ]
            }}
        }) 



    })
});


function setpayload(titre,sub, ref, image)
{
var m = {
            'title': titre,
            'image_url': image,
            'subtitle': sub,
            'buttons': [

                {
                    'type': 'postback',
                    'title': 'postuler',
                    'payload': ref
                },
                {
                    'type': 'postback',
                    'title': 'plus de détail',
                                'payload': ref
                }
            ]
        }

return m ;

}

notant que pour un slide ça marche tré bien controller.hears('offres','message_received, facebook_postback',function(bot,message){

connection.connect("mongodb://localhost/bot",function(err,db){

    var data = db.collection('offres').find().toArray().then(function(data){

        var _under = require("underscore");
        var titre = data[0]['titre'];
        var ref = data[0]['ref'].toString();
        var description = data[0]['description'];

        b = setpayload(titre,description, ref,'https://cdn.pixabay.com/photo/2017/01/13/17/29/hiring-1977803_960_720.jpg');


        bot.reply(message,{
            attachment:{
            'type': 'template',
            'payload': {
                'template_type': 'generic',
                'elements':[b]
            }}
        }) 



    })
});


function setpayload(titre,sub, ref, image)
{
var m = {
            'title': titre,
            'image_url': image,
            'subtitle': sub,
            'buttons': [

                {
                    'type': 'postback',
                    'title': 'postuler',
                    'payload': ref
                },
                {
                    'type': 'postback',
                    'title': 'plus de détail',
                                'payload': ref
                }
            ]
        }

return m ;

}



via shaghabo

What is the difference between net.connect() and socket.connect() in node.js?

I was reading the documentation from the net module in Node.js and I can't see any difference between the methods net.connect() and socket.connect()

Are they exactly the same or is there is some difference?



via moashrafi

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access

server.js where i've declared the permissions

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

app.js

angular.module('app', ['ionic', 'ui.router'])

.config(('$urlRouterProvider', '$stateProvider', function($urlRouterProvider,$stateProvider){
    $urlRouterProvider.otherwise('/');
    $stateProvider
    .state('view',{
      url:'/',
      templateUrl:'js/components/view/view.html',
      controller:'viewCtrl'
    })

}))

view.js

.controller('viewCtrl',['$scope','$state','$http',function($scope,$state,$http)
{   

    $scope.pics=[];
    $http.get('http://localhost:8080/getNewPhoto').then(function(response){
        $scope.pics=response.data;
    },function(err)
    {
        console.error("There's an error"+err);
    })
}])

kindly help me out in this problem I've tried all possible solution but the problem is still there



via Asad Arshad

How does require work when calling node module directly?

When calling a node module directly, e.g. $ ./node_modules/.bin/webpack -d, how is the module aware of how to handle any require functions?

I understand how the require function works, but I'm confused where it is defined.

I had assumed that using something like $ npm start would give context to handle require, but how does Node get involved (and define how to handle require) when the module is called directly?



via charliesneath

I can't evaluate delayed and ordered expressions in javascript

In Javascript (Node), I should run several expressions in an order and in some delays. This doesn't work because all of them run immediately, together in a mixed order;

var i = 0;

function run(){
  console.log(i++);
};

setTimeout(run, 500);
setTimeout(run, 500);
setTimeout(run, 500);
setTimeout(run, 500);

And this is not good:

var i = 0;

function run(){
  console.log(i++);
};

setTimeout(run, 500);
setTimeout(run, 1000);
setTimeout(run, 1500);
setTimeout(run, 1600);

Because It should stop evaluating the next expression. My program flow will go somewhere else and the function will run for no reason.

I need some synchronous functions to run with delay and in my written order. I couldn't implement it.

I don't know If I screwed up the design. I just want to make an online game clicking bot. But this is something different. This web bot should act like a human and click things with a random delay.



via Umut Özdemir

Changing State of React Component in NodeJs Controller

I am doing a simple form in reactjs which is working on a nodejs server. I want to change the state of my form component to hidden once my server verifies that the informations is correct.

Here is the form component:

         import React from 'react'

            class Login extends React.Component {
              constructor(props){
                  super(props);
                  this.state = {
                      showForm: true,
                      email: '',
                      password: ''
                  };
                  this.handleInputChange = this.handleInputChange.bind(this);
                  this.handleSubmit = this.handleSubmit.bind(this);
              }

                handleInputChange(event) {
                    const target = event.target;
                    const name = target.name;
                    const value = target.value;

                    this.setState({
                        [name]: value
                    });
                }

                handleSubmit(event){
                    event.preventDefault();
                     fetch('http://localhost:3000/login', {
                        method: 'POST',
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            email: this.state.email,
                            password :this.state.password,
                        })
                    });
                    this.setState({showForm:false});
                }

              render() {
                return (
                    <div>{this.state.showForm ?
                        <form>
                            <label>
                                email
                                <input
                                    type="text"
                                    name="email"
                                    onChange={this.handleInputChange} />
                            </label>
                            <br />
                            <label>
                                password
                                <input
                                    type="password"
                                    name="password"
                                    onChange={this.handleInputChange} />
                            </label>
                            <input type="submit" value="Valider" onClick={this.handleSubmit}/>
                        </form> : null}
                    </div>
                );
              }
            }

            export default Login;

Here, once I submit, my form posts the information on localhost:3000/login and my server verifies the information with my database thanks to the nodejs controller down there:

    var User = require('../database/Models/User');


    var Users = {

        login : function(req, res){
            var formEmail = req.body.email;
            var formPassword = req.body.password;

            User.findOne({ where: {email: formEmail} }).then(function(user) {
              if(user){
                  if (user.password == formPassword){
                      console.log('User connected');
                  }else{
                      console.log('Password incorrect');
                  }
              }else{
                  console.log('Login incorrect');
              }
            })
        }
    };

    module.exports = Users;

I want that when my controller verified that the information of the form is correct (where i console.log('user connected');) then change the state of the component (normally with setState({showForm:true}) ). But I can't do the import of the component in my controller (to use LoginComponent.setState({showForm:true}) because import is using es6 syntax and nodejs doesn't implement it.

Thanks for the help!



via Aria Groult

Is there a Python module similar to the debug module on npm (Node.js)?

debug is a very useful JavaScript debugging utility. It let's developers selectively enable/disable debugging messages through a DEBUG environment variable (e.g. DEBUG=mypackage node script.js). I was simply wondering if there was an equivalent library/package in Python land.



via Olivier Lalonde

Mogodb Aggregation

this is my user collection

{ 
    "_id" : ObjectId("58e8cb640f861e6c40627a06"), 
    "actorId" : "665991", 
    "login" : "petroav", 
    "gravatar_id" : "", 
    "url" : "https://api.github.com/users/petroav", 
    "avatar_url" : "https://avatars.githubusercontent.com/u/665991?" 

}

this is my repo collection

{ 
    "_id" : ObjectId("58e8cb640f861e6c40627a07"), 
    "repoId" : "28688495", 
    "name" : "petroav/6.828", 
    "url" : "https://api.github.com/repos/petroav/6.828"
}

this is my events collections

{ 
    "_id" : ObjectId("58e8cb640f861e6c40627a08"), 
    "eventId" : "2489651045", 
    "type" : "CreateEvent", 
    "actorLogin" : "petroav", 
    "repoId" : "28688495", 
    "eventDate" : ISODate("2015-01-01T15:00:00.000+0000"), 
    "public" : true         
}

i am trying to do following queries on above data

  1. Return list of all repositories with their top contributor
  2. Find the repository with the highest number of events from an actor (by login). If multiple repos have the same number of events, return the one with the latest event.
  3. Return actor details and list of contributed repositories by login

i tried 3 one by doing this

db.events.aggregate(
   [    {
            $match:{"actorLogin":"petroav"}
        },
        {
            $lookup:{
                from:"repos",
                localField:"repoId",
                foreignField:"repoId",
                as:"Repostory"
                }
        },
        {
            $group:{ _id : "$Repostory", repo: { $push: "$$ROOT" } } 
        }

   ]
).pretty()

please help i new to mongodb



via Mir Rayees Ahmad

Get an _id from mongoose model by name. Nodejs

Problem is - i can't define variable inside this function (console.log is working), and can't find another way how to get _id from this damn model.

 User.findOne({name: name}, function(err, user) {
    var test = user._id;
    console.log(user._id);
});



via Сергей Иванов

How to set up docker elasticsearch with node?

here is my docker-composer.yml file:

db:
    image: mongo
    ports:
        - "27017:27017"
    restart: always
elasticsearch1:
    image: docker.elastic.co/elasticsearch/elasticsearch:5.3.0
    container_name: elasticsearch1
    environment:
      - cluster.name=docker-cluster
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ulimits:
      memlock:
        soft: -1
        hard: -1
      nofile:
        soft: 65536
        hard: 65536
    mem_limit: 1g
    cap_add:
      - IPC_LOCK
    volumes:
      - esdata1:/usr/share/elasticsearch/data
    ports:
      - 9200:9200
web:
    build: .
    volumes:
        - ./:/usr/src/app
    ports:
        - "3000:3000"
    links:
        - db
        - elasticsearch1
    command: npm start

Problem is I get this error:

web_1 | { Error: No Living connections web_1 |
at sendReqWithConnection (/usr/src/app/node_modules/mongoosastic/node_modules/elasticsearch/src/lib/transport.js:211:15) web_1 | at next (/usr/src/app/node_modules/mongoosastic/node_modules/elasticsearch/src/lib/connection_pool.js:213:7) web_1 | at _combinedTickCallback (internal/process/next_tick.js:67:7) web_1 | at process._tickDomainCallback (internal/process/next_tick.js:122:9) message: 'No Living connections' }

I can run elasticsearch in localhost but problem is with node it not working, I using mongoosastic lib for node.



via Vladimir

Koajs routes work with HTTP but broken with HTTPS

I'm setting up HTTPS on my koa2 API with letsencrypt, using the last part of this DigitalOcean guide. I'm using nginx for reverse proxy. Everything works fine with HTTP but with HTTPS my routes are broken, and since this is my first time setting up HTTPS, I'm having a hard time finding the cause. For example, with plain HTTP, making a request to http://myapi.com/api/some-route, I'd see a request looking something like

{ 
  request: { 
  method: 'GET', 
  url: '/api/some-route', 
  header: { 
    'origin': 'https://myapi.com', 
    accept: '*/*' 
  } 
}

With HTTPS it looks like

{ 
  request: { 
  method: 'GET', 
  url: '//some-route', 
  header: {accept: '*/*' } 
} 

The request.url is funky and the origin header is missing. I'm wondering if it's an issue with my nginx config, but having a hard time figuring out where to start.



via harumphfrog