Monday, 12 June 2017

res.render fails in try catch

my res.render fails in my try catch block in express. How can I fix this? Before this I tried it outside of the function. I was following a async await example. I googled around and found the separating the res.render into a separate function but that didn't work either. On the client side the post returns an error 500.

router.post('/placeorder', function(req,res) {
  console.log(JSON.stringify(req.body))
  var order, token, state_id, address, total, payment_id, address, address2, address2b,shipping_id, shipping_method, shipping_array,shipping
  var expMM = req.body.expiry.split('/')[0].replace(/ /g, "")
  var expYYYY = req.body.expiry.split('/')[1].replace(/ /g, "")
  var ccnumber = req.body.number.replace(/ /g , "")
          var cc = {
            "order": {
              "payments_attributes": [
                {
                  "payment_method_id": "4"
                }
              ]
            },
            "payment_source": {
              "4": {
                "number": ccnumber,
                "month": expMM,
                "year": expYYYY,
                "verification_value": req.body.cvc,
                "name": req.body.ccname
              }
            }
          }




        function getState() {
          var getState = {method:'GET', uri: 'https://shop.domeha.com/api/v1/countries/232/states?q[name_cont]=' + req.body.state }
          return new Promise(function(resolve, reject) {
            request(getState, function(err, resp, body) {
              console.log(resp.statusCode != 200)
              if (err || resp.statusCode != 200 && resp.statusCode != 201) return reject(new Error (err || body))
              resolve(body)
            }) // request
          }) // return new promise
        } // function get state

        function createOrder() {
            stepOne = {method:'POST', uri: 'https://shop.domeha.com/api/v1/orders', body: {"order":{"line_items": req.body.items}}, json: true}
            return new Promise(function(resolve, reject) {
              request(stepOne, function(err, resp, body) {
              if (err || resp.statusCode != 200 && resp.statusCode != 201 && resp.statusCode != 202) return reject(new Error (err || body))
              resolve(body)
            })
          })
        }

        function addEmail() {
          stepTwo = {method:'PUT', uri:'https://shop.domeha.com/api/v1/orders/' + number + '.json?order_token=' + token + '&order[email]=' + req.body.email}
          return new Promise(function(resolve, reject) {
            request(stepTwo, function(err, resp, body) {
              if (err || resp.statusCode != 200 && resp.statusCode != 201 && resp.statusCode != 202) return reject(new Error (err || body))
              resolve(body)
            })
          })
        }

        function addAddress() {
          stepThree = {method: 'PUT', uri: 'https://shop.domeha.com/api/v1/checkouts/' + number + '.json?order_token=' + token, body: address, json:true}
          console.log(address)
          return new Promise(function(resolve, reject) {
            request(stepThree, function(err, resp, body) {
             if (err || resp.statusCode != 200 && resp.statusCode != 201 && resp.statusCode != 202) return reject(new Error (err || body))
              resolve(body)
            })
          })
        }


        function addShippingMethod() {
          stepSix = {method: 'PUT', uri:'https://shop.domeha.com/api/v1/checkouts/' + number + '.json?order_token=' + token, body: shipping, json: true}
          return new Promise(function(resolve, reject) {
            request(stepSix, function(err, resp, body) {
              if (err || resp.statusCode != 200 && resp.statusCode != 201 && resp.statusCode != 202) return reject(new Error (err || body))
              resolve(body)
            })
          })
        }

        //function moveToPayment() {
        //  stepFour = {method: 'PUT', uri:'http://shop.domeha.com/api/v1/checkouts/' + number + '/next.json?order_token=' + token}
        //  return new Promise(function(resolve, reject) {
        //    request(stepFour, function(err, res, body) {
        //      if (err) return reject(err)
        //      resolve(body)
        //    })
        //  })
        //}

        function addPayment() {
          console.log(JSON.stringify(cc))
          stepFive = {method: 'PUT', uri: 'https://shop.domeha.com/api/v1/checkouts/' + number + '.json?order_token=' + token, body: cc, json:true}
          return new Promise(function(resolve, reject) {
            request(stepFive, function(err, resp, body) {
              if (err || resp.statusCode != 200 && resp.statusCode != 201 && resp.statusCode != 202) return reject(new Error (err || body))
              resolve(body)
            })
          })
        }

        function confirmOrder() {
          stepSix = {method: 'PUT', uri: 'https://shop.domeha.com/api/v1/checkouts/' + number + '.json?order_token=' + token}
          return new Promise(function(resolve, reject) {
            request(stepSix, function(err, resp, body) {
              console.log(resp.statusCode != 200)
              if (err || resp.statusCode != 200 && resp.statusCode != 201 && resp.statusCode != 202) return reject(new Error (err || body))
              resolve(body)
            })
          })
        }

        function showError(error) {
          res.render('checkouterr', error)

        }

        async function main() {

          try { 

           var one = await getState()
           console.log(one)
            one = JSON.parse(one)
            state_id = one.states[0].id


           address = 
           {
                "order": {
                  "bill_address_attributes": {
                    "firstname": req.body.b_first,
                    "lastname": req.body.b_last,
                    "address1": req.body.b_address,
                    "address2": address2b,
                    "city": req.body.b_city,
                    "phone": req.body.phone,
                    "zipcode": req.body.b_zip,
                    "state_id": state_id,
                    "country_id": 232
                  },
                  "ship_address_attributes": {
                    "firstname": req.body.first,
                    "lastname": req.body.last,
                    "address1": req.body.address,
                    "address2": address2,
                    "city": req.body.city,
                    "phone": req.body.phone,
                    "zipcode": req.body.zip,
                    "state_id": state_id,
                    "country_id": 232
                  }
                }
           }


           var two = await createOrder()
            console.log(two)
            number = two.number
            token = two.token
            total = two.total
            console.log('create order Done')


            var three = await addEmail() 
            console.log('add email done')

            var four = await addAddress() 
            console.log(four)
            console.log('Adding address done')
            shipping_id = four.shipments[0].id

            shipping_array = four.shipments[0].shipping_rates
            var sorted = shipping_array.filter(function(e) {
              return e.shipping_method_id == req.body.shipping
            })
            //throw(sorted)

            shipping = {
              "order": {
                "shipments_attributes": {
                  "0": {
                    "selected_shipping_rate_id": sorted[0].id,
                    "id": shipping_id
                  }
                }
              }
            }

            var five = await addShippingMethod()
            console.log(JSON.stringify(five))

            var six = await addPayment() 
            console.log(six)

            var seven = await confirmOrder()
            console.log(seven)
            //throw(JSON.stringify(eight))

            res.cookie( "orderNumber", number,{ maxAge: 1000 * 60 * 10, httpOnly: false });
            res.cookie( "customerEmail", req.body.email,{ maxAge: 1000 * 60 * 10, httpOnly: false });
            res.render('thankyou')

          } catch (e) {
            console.log('error catch called')
            showError(e)

          }

        }
        main()
}) // route



via QueSo

NodeJS: ENOENT: no such file or directory

I have a function that opens a file (if exists), returns it as response to an API call, and then deletes the file.

function getAttachment(req, res) {
  const filePath = req.params.filePath;
  try {
    const fileStream = fs.createReadStream(filePath);
    res.writeHead(200, { 'content-type': 'application/json' });
    fileStream.pipe(res);
    fs.unlinkSync(filePath);
  } catch (err) {
    console.log(JSON.stringify(err));
    res.sendStatus(404);
    res.end();
  }
}

However, I get this error:

2017-06-12T17:16:00.289105856Z {"errno":-2,"code":"ENOENT","syscall":"unlink","path":"data/myfile"}
2017-06-12T17:16:00.298763021Z events.js:160
2017-06-12T17:16:00.298781839Z       throw er; // Unhandled 'error' event
2017-06-12T17:16:00.298785330Z       ^
2017-06-12T17:16:00.298788100Z 
2017-06-12T17:16:00.298790660Z Error: ENOENT: no such file or directory, open 'data/myfile'
2017-06-12T17:16:00.298795535Z     at Error (native)
2017-06-12T17:16:00.306091265Z 
2017-06-12T17:16:00.312570210Z npm info lifecycle express-mongoose-es6-rest-api@1.0.0~start:dist: Failed to exec start:dist script
2017-06-12T17:16:00.312591284Z npm ERR! Linux 4.4.0-79-generic
2017-06-12T17:16:00.312763931Z npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "start:dist"
2017-06-12T17:16:00.312952665Z npm ERR! node v6.9.4
2017-06-12T17:16:00.313133777Z npm ERR! npm  v3.10.10
2017-06-12T17:16:00.313309768Z npm ERR! code ELIFECYCLE
2017-06-12T17:16:00.313484507Z npm ERR! express-mongoose-es6-rest-api@1.0.0 start:dist: `node dist/index.js`
2017-06-12T17:16:00.313491824Z npm ERR! Exit status 1
2017-06-12T17:16:00.313664060Z npm ERR!

How can I make this work without the system going down even if the file doesn't exist?



via Arturo

Displaying user information on Google Map on click of the location using node js, express and mongodb

I am doing a small project which takes user information like name, age, location etc and display it on the Google map on click of that location.

I have completed the first part i.e., taking user information using node js, express and Mongo db.

I am not understanding how to go to next part and display that information on Google maps on click of that location.

Any tutorial or pointers would be helpful on how to go forward. Thanks.



via Sarvesh Kulkarni

I want to reuse angular2 components into other platform like java, JS, .net

Can u use other platforms like JAVA,.Net components into angular.js2? I am developing UI template in angular.js2 where we should able to plug any template(Developed in Java, .net) into angular2 tool.

is there any way that i can plug and integrate any platform into angular.js2??

Response will be appreciated.



via Yash Dabhi

babel-register issues when using css modules

So I have a react app that's using css modules for styling. I'm trying to make the app server rendered, however since it wasn't made with this in mind, I'm using import everywhere which is breaking node since import isn't supported there yet, and as a workaround I decided to use babel-register for the time being until I can convert the rest of the codebase to something more production friendly.

The issue I'm facing is that since I'm using css modules along with babel-register, when I import my sass file I'm getting

header.scss: Leading decorators must be attached to a class declaration (1:7)
> 1 | @media all {
    |        ^
  2 |
  3 |   .header {
  4 |     width: 100%;

This seems to make sense, since it looks like babel-register is expecting all imports to be js files, I'm not sure if there are any workarounds with this or if I should take a different approach all together. The end goal is to be able to hit the url, and have the html returned contain the rendered components instead of just the placeholder div my app targets.

Any help is appreciated! Thanks =p



via Colton

socket.io connect external address with nodejs socket.io-client

I have this code in NODE.JS to connect to socket.io server and dont work.

var io = require('socket.io-client');

var socket = io('https://pt53.tribalwars.com.pt:8081/game', {
        query: "sessid=" + tribal.sid + "&village_id=" + tribal.village_id + "&screen=overview",
        rememberUpgrade: !0 //true
})

socket.on('connect', function(){
    console.log("CONNECTED")
    console.log(socket.id);
});

The value of

tribal.sid // Session ID

and

tribal.village_id //Village ID

is from cookies after login in the game. I already have it working.

HTML

Here is the webpage code in some script tag (pt53.tribalwars.com.pt) WORLD 53

Example: Connection.connect(ip,port,sessionid,protocol)

 Connection.connect('pt53.tribalwars.com.pt', 8081, '88ab75e0bdf2', true);

JS

file (game.js) METHOD connect:

    connect: function(e, i, n, o) {
        var t = this;
        if ("android" !== window.game_data.device) {
            if (!this.isSupportedBrowser()) return void this.showUnsupportedBrowserNotice();
            if (!window.iosappdata || $.inArray("socket.io", window.iosappdata.capabilities) === -1) {
                if ("undefined" == typeof io) return void Connection.debug("node", "Couldn't connect to backend: socket.io not available");
                var a = "undefined" != typeof game_data.village ? game_data.village.id : 0,
                    r = {
                        query: "sessid=" + n + "&village_id=" + a + "&screen=" + game_data.screen,
                        rememberUpgrade: !0
                    };
                Boolean($.cookie("websocket_available")) === !0, this.socket = io.connect((o ? "https://" : "http://") + e + ":" + i + "/game", r);
                var s = this.socket;
                this.socket.on("connect", function() {
                    Connection.debug("Connected to backend"), $(Connection).trigger("connected");
                    for (var e = 0; e < t.emit_queue.length; e++) {
                        var i = t.emit_queue[e];
                        s.emit(i[0], i[1])
                    }
                    t.emit_queue = []
                }), this.socket.io.engine.on("upgrade", function(e) {
                    $.cookie("websocket_available", !0)
                }), this.socket.on("connect_error", function() {
                    $(Connection).trigger("connect_error")
                }), this.socket.on("disconnect", function(e) {
                    Connection.debug("disconnected"), $(Connection).trigger("disconnected")
                }), this.socket.on("error", function(e) {
                    "Invalid session" === e && $(Connection).trigger("disconnected")
                }), $.each(this.pending_handlers, function(e, i) {
                    Connection.registerHandler(e, i)
                })
            }
        }
    },

I can post more code about this file if needed.

Conclusion

I wonder if it's possible, I can not connect, can it be missing cookies or something? The address is correct and the query option is also correct :/



via backnd

simple aws-sdk-mock times out without calling callback

I am currently writing some unit tests in nodejs using the mocha framework. Recently, I've been trying to learn how to mock the Amazon Web Services SDK, using the aws-sdk-mock module and the explanations on the same page.
I have come up with a short test which is supposed to mock the DynamoDB DocumentClient 'get' operation, call it once, and log the return value. Here is the code:

var AWS = require('aws-sdk');
var AwsMock = require('aws-sdk-mock');
describe("xyz", function() {
    it('should call "get" on mock database', function(done) {
        AwsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
            callback(null, {
                Item: {
                    Key: 'Value'
                }
            });
        });
        var dynamoDb = new AWS.DynamoDB.DocumentClient();
        dynamoDb.get({}, function(err, data) {
            console.log('data: ' + JSON.stringify(data));
            done();
        });
    });
});

However, for some reason that is escaping me, this test keeps failing with a timeout error, as the callback error is seemingly never called. This is the full test result:

xyz
    1) should call "get" on mock database

  0 passing (2s)
  1 failing

  1) xyz should call "get" on mock database:
     Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

npm ERR! Test failed.  See above for more details.

I believe I followed the explanations on the aws-sdk-mock page pretty closely (I copied the mock part without changes), and I cannot find the fault in this code. I searched google and Stackoverflow, but couldn't find a similar question, so can anyone tell me where the problem is?

Thanks in advance.



via deadpool