Node.js从我的Ajax前端接收多个请求

时间:2019-06-14 13:32:55

标签: javascript node.js ajax express post

由于某些原因,Ajax会多次将get和post请求发送到我的Express后端。

例如,当我创建一个新订单时,有时它将发送该请求两次或三次,并多次创建该订单。或者,当我想查看一种货币的实时价格时,它将一遍又一遍发送GET请求。

示例1:获取货币价格

这是我的前端javascript:

function getSymbolPrice(exchange, symbol) {
$.ajax({
    url: '/getSymbolPrice/' + exchange + '/' + symbol,
    method: 'GET',
    contentType: 'application/json',
    success: async function (response) {
        symbol_price = parseFloat(response.price);
    }
});
}

还有我的后端:

app.get('/getSymbolPrice/:exchange/:symbol', isLoggedIn, async function (req, res, next) {
    var exchange = req.params.exchange;
    var symbol = req.params.symbol;
    var url;

    if (exchange.toLowerCase() == "binance") {
        url = 'https://api.binance.com/api/v1/ticker/price?symbol=' + symbol.toUpperCase();
    }

    if(symbol.toUpperCase() != "NULL") {
        await request({
        uri: url,
        json: true
    }, function (error, response, body) {
        if (error) {
            console.log(error);
        } else if (!error && response.statusCode === 200) {
            //console.log(body);
            res.send(body);
        } else {
            console.log(response);
        }
    });

    }
});

示例2:发布新订单 前端html

<form id="market_order_buy_form">


<fieldset>
      <div class="d-flex m-0 w-100 mb-2">
         <p class="p-0 m-0 blue-text text-format-08 justify-content-start">BUY</p>
         &nbsp;
         <p class="p-0 m-0 blue-text text-format-08 mr-auto exchange_balance_base_symbol">BTC</p>
         <p class="p-0 m-0 text-color text-format-08 exchange_balance_quote"> 865&nbsp;</p>
         &nbsp;
         <p class="p-0 m-0 blue-text text-format-08 exchange_balance_quote_symbol">USDT</p>
      </div>
      <div class="input-group input-group-sm mb-2 disabled-cursor">
         <input type="text"
            class="form-control light-border text-format-08 text-color box-color-bg disabled"
            value="Market Price" id="initial_market_buy_price">
         <div class="input-group-append">
            <span class="input-group-text text-format-08 text-color light-border light-box-color-bg"
               id="initial_market_buy_price_symbol">USDT</span>
         </div>
      </div>
      <div class="input-group input-group-sm mb-2">
         <input type="text"
            class="form-control light-border text-format-08 text-color box-color-bg"
            placeholder="Quantity" id="initial_market_buy_quantity">
         <div class="input-group-append">
            <span class="input-group-text text-format-08 text-color light-border light-box-color-bg"
               id="initial_market_buy_quantity_symbol">&nbsp;BTC&nbsp;&nbsp;</span>
         </div>
      </div>
      <div class="d-flex align-self-end m-0 w-100 mb-0">
         <button type="button" class="btn btn-sm btn-default waves-effect w-100 py-2 m-0 mr-auto initial_market_buy_btn" onclick="submit_bot_order()">BUY</button>
         <div class="form-check pl-2 pl-0 initial_buy_checkbox" style="display: none">
            <input type="checkbox" class="form-check-input" checked disabled>
            <label class="form-check-label text-format-08"></label>
         </div>
      </div>
   </fieldset>
</form>

前端javascript

function submit_bot_order() {

var trade = {}; // data from input fields
$.ajax({
    url: '/createBotOrder/' + $('#accounts').val(),
    method: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(trade),
    success: function (response) {
        alert(response);
    }
});
setTimeout(refresh_fields, 2000); //just resets all fieldsets

}

Nodejs后端

app.post('/createBotOrder/:account', isLoggedIn, function (req, res, next) {
    User.findById(req.user._id, function (err, doc) {
        if(err){
            console.log(err);
        }

        for (var i in doc.user.exchange_accounts) {
            if (doc.user.exchange_accounts[i]._id == req.params.account) {
                req.body.keys = [doc.user.exchange_accounts[i].initialize.api_key, doc.user.exchange_accounts[i].initialize.secret_key, doc._id, doc.user.exchange_accounts[i]._id];
            }
        }
        new_order.initialize_trade(req.body);
    });

});

1 个答案:

答案 0 :(得分:0)

您似乎并未在所有后端流程中发送响应。例如,在/createBotOrder/:account中,您至少应包含res.sendStatus(200)

找不到用户时,您还应该返回响应:

app.post('/createBotOrder/:account', isLoggedIn, function (req, res, next) {
    User.findById(req.user._id, function (err, doc) {
        if(err){
            console.log(err);
            return res.sendStatus(404);
        }

        for (var i in doc.user.exchange_accounts) {
            if (doc.user.exchange_accounts[i]._id == req.params.account) {
                req.body.keys = [doc.user.exchange_accounts[i].initialize.api_key, doc.user.exchange_accounts[i].initialize.secret_key, doc._id, doc.user.exchange_accounts[i]._id];
            }
        }
        new_order.initialize_trade(req.body);
        res.sendStatus(200)
    });

});

我认为浏览器正在超时并再次发出请求以恢复(我以前见过这种情况)。