[英]Handling POST request and redirecting with AngularJS and Python Flask
我一直在使用AngularJS和Flask進行一個簡單的網站項目。 在這家商店中,用戶可以檢查要購買的產品,下訂單時,所有內容都會保存在postgresql數據庫中,並且用戶將被重定向到相應的頁面(由於某些問題,運輸完成或運輸失敗)。 我正在使用try-except處理存儲過程中可能出現的錯誤,並且無法將用戶重定向到適當的url。 將值插入數據庫后,將不會發生任何事情。 我在main.html中使用ng-view 。
這是我的server.py :
@app.route('/')
def mainPage():
return current_app.send_static_file('main.html')
@app.route('/shipping')
def shippingPage():
return current_app.send_static_file('main.html')
@app.route('/shippingfailed')
def shippingFailedPage():
return current_app.send_static_file('main.html')
@app.route('/placeorder', methods=['GET','POST'])
def placeOrder():
try:
data = request.get_json()
productsBought = data.pop('products')
order = orders(**data)
session.add(order)
session.flush()
mydict = {}
mydict["orderno"] = order.orderno
for product in productsBought:
mydict["productno"] = product
details = orderdetails(**mydict)
session.add(details)
session.flush()
session.commit()
return redirect(url_for('shippingPage'))
except Exception:
session.rollback()
raise
return redirect(url_for('shippingFailedPage'))
finally:
session.close()
這是我的app.js :
angular.module('shoppingCart', ['ngRoute'])
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$routeProvider
.when('/', {
templateUrl: 'static/cart.html'
})
.when('/cart', {
templateUrl: 'static/cart.html'
})
.when('/checkout', {
templateUrl: 'static/checkout.html'
})
.when('/shipping', {
templateUrl: 'static/shipping.html'
})
.when('/shippingfailed', {
templateUrl: 'static/shippingfailed.html'
});
}])
.controller('cartCtrl', ['$scope', '$http', '$filter', function($scope, $http, $filter){
this.placeOrder = function(){
vm.customer.price = $filter('calculateTotal')(this.cartItems);
this.jsonCustomer = JSON.stringify(vm.customer);
$http.post('/placeorder', this.jsonCustomer, {headers: {'Content-Type': 'application/json'} });
}
}])
這是我的checkout.html :
<div class="text-right">
<a type="button"
class="btn btn-danger"
ng-if="vm.cartItems.length !=0"
ng-click="vm.placeOrder()"
href="#/placeorder">Place Order</a>
</div>
因此,總而言之,預期的行為是當用戶使用checkout.html並單擊“下單”時,他們將被重定向到/ placeorder ,然后服務器在try-except中處理POST請求並將其重定向據此。
您不應該在flask中的API端點中返回重定向。 而是返回一個URL以進行重定向,然后檢查POST的結果並在前端應用程序中進行重定向。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.