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

No comments:

Post a Comment