Home > OS >  redirect a POST to GET request
redirect a POST to GET request

Time:01-02

I'm trying to understand what is the best way a POST request can be redirected to a GET request. for example -

POST /redirect HTTP/1.1
Host: www.example1.com

url=www.example2.com

and i've created the following flask to help me with that :

from flask import Flask,request, redirect

app = Flask(__name__)

@app.route('/redirect',methods=['POST'])
def redire():
    url = request.form['url']
    return redirect('https://www.example2.com', code=307)

if __name__ == '__main__':
   app.run(host='0.0.0.0', port=8888)

the "issue" in my case, is that the request that is being sent to

https://www.example2.com

is also a POST request which is not what i wanted.

Consider that I don't "care" about the body that needs to be sent to the

https://www.example2.com

endpoint, what is the best way to do so without any user intervention (meaning that I'm aiming for an auto redirect).

Note: I've tried to do it via PHP but I can't seem to figure it out.

Apologies if something is not clear.

CodePudding user response:

In order to redirect a POST request to a GET request, you need to use code=303 because it requires the client to use the GET method to retrieve the requested resource.

@app.route('/redirect',methods=['POST'])
def redire():
    url = request.form['url']
    return redirect('https://www.example2.com', code=303)

CodePudding user response:

the server

from flask import Flask, redirect

app = Flask(__name__)


@app.route('/redirect', methods=['POST'])
def redire():
    return redirect('http://127.0.0.1:8888/get')


@app.route('/get', methods=['GET'])
def iam_get():
    return {"code": "ok"}


if __name__ == '__main__':
   app.run(host='0.0.0.0', port=8888)

the client

import requests


data = requests.get("http://127.0.0.1:8888/get")
print(data.text)

data = requests.post("http://127.0.0.1:8888/redirect")
print(data.text)

the result as follows

{"code":"ok"}

{"code":"ok"}
  • Related