Sunday, 7 May 2017

UnhandledPromiseRejectionWarning: Unhandled promise rejection NodeJS MSSQL

I'm having a play about testing out some NodeJS setting up an API.

However when SQL returns an error about NULL columns my http call just hangs and you can see the error in the node console.

The error I get is "node:7397) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): RequestError: Cannot insert the value NULL into column 'FeatureEntryId', table 'testdb STING.dbo.J_ProductFeaturesRelation'; column does not allow nulls. INSERT fails."

Here is the code.

//Add or update feature relations
var insertFeatureRelation = (callback, productid, featureid) => {
    console.log(productid + ' ' + featureid)
    var conn = new sql.Connection(settings.dbConfig())
    conn.connect().then(function (conn) {
        var request = new sql.Request(conn);
        request.input('productid', sql.VarChar, productid);
        request.input('featureid', sql.VarChar, featureid);
        request.execute('PM_InsertFeatureRelation').then(function (recordsets, returnValue, affected) {
            callback(recordsets)
        })
    }).catch(function (err) {
        console.log('ffs');
        callback(null, err);
    });
}
exports.insertFeatureRelation = function (req, resp, productid, featureid) {
    insertFeatureRelation(function (data, err) {
        if (err) {
            httpMsgs.show500(req, resp, err)
        } else {
            httpMsgs.sendJSON(req, resp, data)
        }
        resp.end();
    }, productid, featureid)
};

The code works fine if the stored procedure runs fine however the error just never actually somes through to the page.

Here is the content of the httpMsgs...

exports.show500 = function(req, resp, err) {
    console.log('heree')
        resp.writeHeader(500, {"Content-Type": "application/json"});
        resp.write(JSON.stringify({data: "Error:" + err}))
};

exports.sendJSON = function(req, resp, data) {
    if (data){
        resp.writeHeader(200, {"Content-Type": "application/json"});
        resp.write(JSON.stringify(data));
    }
}

Thanks for looking have a great day!



via Adam91Holt

Inconsistent behavior npm

I'm using npm install with advanced range, e.g. npm i karma@^1.0.0 and for Linux and OSX I get the latest version of package, but for windows platform, npm ignores range (caret symbol) and installs v.1.0.0

According to npm docs, I have to enclose version range with quotes. So, this npm i karma@"^1.0.0" works on windows properly.

Note that most version ranges must be put in quotes so that your shell will treat it as a single argument.

But why does it affect only windows? What might be the cause of this inconsistency?

npm - v.4.0.5

node - v.7.4.0

Thanks.



via Bob

Res.render in POST request (auth system) does not work, why?

The below is supposed to be an authentication system, but I face a problem. On a button click on the front-end, this is what happens:

firebaseAUTH.signInWithEmailAndPassword(email, password).then(function (user) {
    console.log('user has signed in with e-mail address: '+user.email+' and user ID: '+user.uid)
    firebaseAUTH.currentUser.getToken(true).then(function(idToken) {
    // Send token to your backend via HTTPS (JWT)
    $.ajax(
    {
      url: '/auth',
      type: 'POST',
      data: {token: idToken},
      success: function (response){
      }
})
}).catch(function(error) {
// Handle error
console.log(error.message)
})

And then with res.render I am trying to render a page, but it simply does not work. What am I missing here? Why does it not render at all (I do have a template file called like that, so it should work).

app.post('/auth', function(req,res,next){
  var token = req.body.token
  admin.auth().verifyIdToken(token)
    .then(function(decodedToken) {
      console.log(decodedToken.uid)
      res.render('index', {userID: uid})
    }).catch(function(error) {
      console.log(error.message)
    })
})



via huzal12

How to connect to socket.io using Java and NodeJS

There aren't very many specific guides out there, and I've tried to connect before. Would anyone be willing to write out some specific instructions?



via Jeff smith

Sockiet.io in SWIFT 3 -> Node.js (Hieroglyphs instead of Cyrillic chars)

Good day! I'm trying to send msg via socket.io from swift 3 to my node server. Everything ok until i'm trying to send msg with Cyrillic chars -> as a result i get a Hieroglyphs on server.

app:

let msgSocket:Parameters = ["opid": self.msgList[row].sitter_id, "myid": self.msgList[row].client_id, "msg": msgText.text]
print(msgText.text)

Please help



via Konstantin Kovalenko

Hosting pure angularjs app on google app engine

I have an angular js app with following structure enter image description here

my app folder look like

enter image description here

the app does use any back end interaction for now but in future its gonna interact with a separate app engine java project . I want to host this angularjs app to google app engine but I am not able to understand the right configuration . I am more confused how do I set up the app.yaml for google app engine ... and is it necessary to have a main.py file as at present I do not have any handler



via John

Websockets & NodeJS - Changing Browser Tabs & Sessions

I've started writing a node.js websocket solution using socket.io.

The browsers connects to the node server successfully and I get see the socket.id and all config associated with console.log(socket). I also pass a userid back with the initial connection and can see this on the server side to.

Question: I'm not sure the best way to associate a user with a connection. I can see the socket.id changes every page change and when a tab is opened up. How can I track a user and send 'a message' to all required sockets. (Could be one page or could be 3 tabs etc).

I tried to have a look at 'express-socket.io-session' but I'm unsure how to code for it and this situation.

Question: I have 'io' and 'app' variables below. Is it possible to use the 2 together? app.use(io);

Essentially I want to be able to track users (I guess by session - but unsure of how to handle different socket id's for tabs etc) and know how to reply to user or one or more sockets.

thankyou

// Required Modules
var app = require('express')();
var server = require('http').createServer(app);
var socketio = require('socket.io');
var database = require('./includes/database.js');
//var sharedSession = require('express-socket.io-session');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var redisStore = require('connect-redis')(expressSession);


// Cookie & Session Config
app.use(cookieParser());
app.use(expressSession({
    store: new redisStore({ host: 'elasticache.content.dating', port: 3679 }),
    name: 'dating-websocket-session',
    secret: "asd7fha0ds6fa6sdfia6sdgfia6sdfia63wf",
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true, maxAge: 604800 }
}));


// Listener
server.listen(9999, '127.0.0.1', function() {
    console.log('HTTP NodeJS Express Server Listening on: http://localhost:9999\n');
});
var io = socketio.listen(server);


// Server Success Response
app.disable('x-powered-by');
app.get('/', function(req, res) {
    var headers = {};
    headers["Access-Control-Max-Age"] = '3600';
    headers["Access-Control-Allow-Methods"] = "POST";
    headers["Access-Control-Allow-Headers"] = "Content-Type";
    res.writeHead(200, headers);
    res.end();
});


// Share session with io sockets
//io.use(sharedSession(session));


// WebSocket Initialization
var socketList = new Array();
io.on('connection', function(socket) {
    socket.emit('message', 'Server Connected...');

    // Options
    // console.log(socket); -- Show All Socket Config
    // socket.id - Socket ID

    // Connect
    socket.on('clientRequestConnection', function (userid) {
        socket.userid = userid;
        socketList.push(socket);
        console.log('Sockets('+socketList.length+'): '+socket.userid+' <> '+socket.id);


    });

});



via Adam