我有一個http post請求,但當我調用api時它會被觸發兩次。在節點服務器上調用api時,角度post請求運行兩次
基本上我知道節點是異步的,所以可能會等待運行sql來獲取數據,但不知道如何解決它。我的代碼如下:
$http({ method: 'POST',
url: '/api/updateBooking',
data: JSON.stringify({'booking' : selectedItem }),
headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
if (data == "true")
{
$scope.updateSuccess = true;
}
}).
error(function (data, status, headers, config) {
//hits this when unauthorized.
$scope.invalid = true;
});
因此,一旦上面的代碼運行它會直接進入成功,然後錯誤,但返回的數據。但在它傳遞數據之後立即進行。
我的服務器代碼是低於被稱爲
一個
pp.post('/api/updateBooking', function(req,res)
{
var booking = req.body.booking;
var success = "false";
console.log("req.booking=", booking.Date1);
// just update the booking regardless as the booking is selected and is valid.
console.log(booking);
var bookingSql = 'SELECT * FROM Booking WHERE ' + booking.BookingID + '= ID ';
connection.query(bookingSql, function(err,result){
console.log(err);
if(err) {success= false;}
console.log('here result=', result);
//if record found then ok to proceed
if (result != null)
{
var updateBookingSQL = 'UPDATE Booking SET ? WHERE ID = ? ';
var bookingFields = { Date1: booking.Date1,
Date1AMPM: booking.Date1AMPM,
Date2: moment(booking.date2).format('YYYY-MM-DD'),
Date2AMPM: booking.Date2AMPM,
}
console.log('booking fields', bookingFields);
//go and do the update using the bookingID
connection.query(updateBookingSQL, [bookingFields, booking.BookingID], function(err,result)
{
console.log(err);
if (err) {success="false";}
if (result != null)
{
console.log('update booking result', result);
if (result.changedRows == 1)
{
console.log('changed row', result.changedRows);
success = "true";
}
}
res.send(success);
console.log('result of update====', success);
});
}
});
console.log('success=', success) ;
});
任何想法將是巨大的
你怎麼稱之爲$ http?你確定它沒有被觸發兩次? – Thilo
你能澄清一下你的意思嗎?你的意思是'$ http POST'被調用兩次?或者您是否注意到兩個POST被髮送到您的服務器,即使您只希望瀏覽器創建一個POST? – sabhiram
只是一次當我點擊按鈕 – tjhack