Make a Post Request While Redirecting in Flask

Make a POST request while redirecting in flask

The redirect function provided in Flask sends a 302 status code to the client by default, and as mentionned on Wikipedia:

Many web browsers implemented this code in a manner that violated this standard, changing
the request type of the new request to GET, regardless of the type employed in the original
request (e.g. POST). [1] For this reason, HTTP/1.1 (RFC 2616) added the new status codes
303 and 307 to disambiguate between the two behaviours, with 303 mandating the change of
request type to GET, and 307 preserving the request type as originally sent.

So, sending a 307 status code instead of 302 should tell the browser to preserve the used HTTP method and thus have the behaviour you're expecting. Your call to redirect would then look like this:

flask.redirect(flask.url_for('operation'), code=307)

How to send POST request using flask.redirect?

It is not possible to redirect POST requests.
More info is here.

Change value from post request when redirecting in Flask

may be this example helps

@app.route('/nextpage', methods=['POST'])
def nextpage():
page = int(request.form['page'])
page = cb.next_page(page)

return redirect(url_for('community', page=page), code = 307)
@app.route('/community', methods=['POST'])
def community():
page = request.args.get('page')
docs, page = cb.show(page)

return render_template('community.html', posts = docs, ID = ID, page = page)

Flask not redirecting after POST request sent from JavaScript

This line sends and XHR request with the 'POST' method.

xhr.open("POST", "/addTokens");

You hit these lines on your sever:

print("Redirecting to index")
return redirect(url_for('index'))

So you send a redirect response back, however, you don't deal with it in your JS. (Klaus D bet me to it, but XHR don't do redirects).

You then do a 'GET' request back to /addTokens

window.location.href = "/addTokens"

Which is why you never get back to your index.



Related Topics



Leave a reply



Submit