无法在Heroku Node JS应用中触发发布请求

时间:2020-10-26 19:15:13

标签: javascript node.js heroku

我的node js应用在localhost上运行正常。部署到heroku之后,首页已成功加载,但是当我单击ID为paybutton的按钮时,发帖请求未发送。在浏览器控制台中错误为ERR_Connection_Failed。 paybutton click事件是在main.js中处理的,而从main.js中,我正在发送发布请求,该请求是在app.js文件中处理的。

app.js文件

const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
mongoose = require("mongoose");
Customer = require("./models/customer");
var util = require("./utils/id");
var token = require("./utils/token");
var payment = require("./utils/payment");
const app = express();
const port = process.env.PORT || 3000;
const cors = require('cors');

app.use(cors());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
var path = require('path');
const customer = require('./models/customer');

app.use(express.static(path.join(__dirname + '/views', '')));
app.use(express.static(path.join(__dirname + '/utils', '')));

mongoose.connect("mongodb://https://paysafe-payment-app.herokuapp.com:3000/paysafe");

app.all('/*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header("Access-Control-Allow-Headers", "X-Requested-With , token");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header("Access-Control-Expose-Headers", "token");
    next();
});

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

app.post("/token", function (req, res) {
    findpaysafe = {
        "email": req.body.email
    }
    console.log(findpaysafe)
    //checking whether customer exists in database
    customer.find(findpaysafe, async function (err, paysafe) {
        if (err) {
            console.log(err);
        } else {
            if (paysafe.length == 0) {
                await util.getId(req.body,
                    function (result) {
                        // console.log(result);
                        var newpaysafe = {
                            payid: result,
                            email: req.body.email
                        }
                        console.log(newpaysafe)
                        //creating customer in database
                        customer.create(newpaysafe, async function (err, newCustomer) {
                            if (err) {
                                // console.log(err);
                            } else {
                                paysafe = newCustomer;
                                console.log("paysafe**********", paysafe)
                                await token.getToken(paysafe.payid, function (result) {
                                    res.send({
                                        token: result
                                    });
                                })
                                // console.log("added",newlyCreated)
                            }
                        });
                    });
            } else {
                console.log("paysafe", paysafe)
                await token.getToken(paysafe[0].payid, function (result) {
                    res.send({
                        token: result
                    });
                })
            }
        }
    });

});

app.post("/payment", async(req, res) => {
    console.log(req.body);
    await payment.onPay(req.body, function (result) {
        res.send({
            data: result.status
        });
    });
});

app.listen(port, () => console.log(`listening`));

前端文件

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Payment Page</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <link rel="stylesheet" type="text/css" href="./style.css">
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script type="text/javascript" src="./main.js"></script>
        <script src="https://hosted.test.paysafe.com/checkout/v2/paysafe.checkout.min.js"></script>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-8">
                    <h1>Complete Payment</h1>
                    <form class="cf">
                        <div class="half left cf">
                            <div class="form-row">
                                <div class="form-group col-md-6">
                                    <input type="text" id="firstname" placeholder="First Name">
                                </div>
                                <div class="form-group col-md-6">
                                    <input type="text" id="lastname" placeholder="Last Name">
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group col-md-12">
                                    <input type="email" id="email" placeholder="Email Id">
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group col-md-12">
                                    <input type="number" id="phone" placeholder="Phone Number">
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group col-md-6">
                                    <input type="text" id="city" placeholder="City">
                                </div>
                                <div class="form-group col-md-6">
                                    <input type="text" id="zip" placeholder="Zip Code">
                                </div>
                            </div>
                            <input type="text" id="amount" placeholder="Amount">
                            <br>
                            <div>
                                <input type="submit" class="btn" id="paybutton" value="Continue">
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>

JS文件-main.js

$(document).ready(function () {
    $("#paybutton").click(function (event) {
        event.preventDefault();
        Pay();
    });
});

async function Pay() {
    //get data
    let email = document.getElementById("email").value;
    let firstName = document.getElementById("firstname").value;
    let lastName = document.getElementById("lastname").value;
    let phone = document.getElementById("phone").value;
    let city = document.getElementById("city").value;
    let zip = document.getElementById("zip").value;
    let amount = document.getElementById("amount").value;
    var token

    $.ajax({
        url: "https://paysafe-payment-app.herokuapp.com:3000/token",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify({
            'email': email,
            'phone': phone,
            'firstName': firstName
        }),
        success: function (result) {
            token = result.token;

            billingAddress = {
                city: city,
                street: 'abc',
                zip: zip,
                country: 'US',
                state: 'CA'
            }
            customer = {
                firstName: firstName,
                lastName: lastName,
                email: email,
                phone: phone,
                dateOfBirth: {
                    day: 1,
                    month: 6,
                    year: 1989
                }
            }

            function uuidv4() {
                return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                    var r = Math.random() * 16 | 0,
                        v = c == 'x' ? r : (r & 0x3 | 0x8);
                    return v.toString(16);
                });
            }
            checkout(token, billingAddress, customer, amount, uuidv4())
        }
    });

    function checkout(token, billingAddress, customer, amount, uuid) {
        paysafe.checkout.setup("cHVibGljLTc3NTE6Qi1xYTItMC01ZjAzMWNiZS0wLTMwMmQwMjE1MDA4OTBlZjI2MjI5NjU2M2FjY2QxY2I0YWFiNzkwMzIzZDJmZDU3MGQzMDIxNDUxMGJjZGFjZGFhNGYwM2Y1OTQ3N2VlZjEzZjJhZjVhZDEzZTMwNDQ=", {
            "currency": "USD",
            "amount": parseInt(amount) * 100,
            "singleUseCustomerToken": token,

            "customer": customer,
            "billingAddress": billingAddress,
            "paymentMethodDetails": {
                "paysafecard": {
                    "consumerId": "1232323"
                },
            },
            "environment": "TEST",
            "merchantRefNum": uuid,
            "canEditAmount": false,
            "payout": false,
            "payoutConfig": {
                "maximumAmount": 10000
            }
        }, function (instance, error, result) {
            if (result && result.paymentHandleToken) {
                $.ajax({
                    type: "POST",
                    url: "https://paysafe-payment-app.herokuapp.com:3000/payment",
                    contentType: "application/json",
                    data: JSON.stringify({
                        'token': result.paymentHandleToken,
                        'amount': result.amount
                    }, ),
                    success: (data) => {

                        // show payment status             

                        if (data.data == "COMPLETED") {
                            instance.showSuccessScreen("Payment Successful!");
                        } else {
                            instance.showFailureScreen("Payment was declined. Please try again after some time.");
                        }
                        setTimeout(function () {
                            window.location.replace(window.location.href);
                        }, 5000);
                    }
                });
            } else {
                console.log("error");
                alert("Please keep in mind -----" + error.detailedMessage)
            }
        }, function (stage, expired) {
            switch (stage) {
                case "PAYMENT_HANDLE_NOT_CREATED":
                case "PAYMENT_HANDLE_CREATED":
                case "PAYMENT_HANDLE_REDIRECT":
                case "PAYMENT_HANDLE_PAYABLE":
                default:
            }
        });
    }
}

0 个答案:

没有答案