How to redirect from a JSON response?

谁说我不能喝 提交于 2021-01-28 05:51:47

问题


So I am trying to use Flask and a Javascript uploader(Dropzone) to upload files and redirect after the upload is complete. Files are getting uploaded fine, but using the traditional redirect in flask:

return (redirect ("http://somesite.com"))

Does nothing, page does not change. I think this is because of this: The request headers of the files being sent are set to Accept:"application/json", and the response headers are being sent in <"text/html; charset=utf-8" How can I return a json response and then redirect from it? Just doing

 return (redirect (jsonify("http://somesite.com")))

gives an error:

ValueError: dictionary update sequence element #0 has length 1; 2 is required

I know browsers won't redirect from Json headers anyway. How can I send the url to redirect to from Flask back to my JS app clientside and redirect from there? I already tested this with a normal HTML form to submit the files and it worked perfectly so I'm pretty sure it is the JSON issue. Thank you.


回答1:


You can set the mimetype for the response:

response = redirect('http://somesite.com')
response.mimetype = 'application/json'

return response

Or:

return make_response(redirect('http://example.com'), mimetype='application/json')



回答2:


If you are using AJAX calls, then you need to return the destination location in the JSON response and then set the value of window.location.href to this in your JS code.



来源:https://stackoverflow.com/questions/22268823/how-to-redirect-from-a-json-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!