javascript - Flask - 如何在获取帖子后重定向
问题描述
目前我有一个搜索页面,它接受输入然后使用它来搜索 api 的数据。我像这样将页面中的输入发布到服务器
fetch('/search', {
method: 'POST',
headers: new Headers({'Content-Type': 'application/json'}),
body: JSON.stringify({data: input,token: token,})
})
.then(function (data) {
console.log('Request success: ', data);
})
.catch(function (error) {
console.log('Request failure: ', error);
});
服务器上的输入是这样设置的
req = request.get_json()
input = req['data']
input
然后使用上面的 from 搜索并返回结果。我需要使用server side result
来确定将用户重定向到哪里。我会window.location.href = '/search/bad'
选择重定向之类的东西,但我不知道搜索是否好,直到result.is_success()/error()
下面
if result.is_success():
print('search was success ',result.body)
return redirect(url_for('search_bad'))
elif result.is_error():
print('search was failure ',result.errors)
return redirect(url_for('search_bad'))
我在终端看到的是
search was failure ....
127.0.0.1 - - [01/Nov/2020 14:33:54] "POST /search HTTP/1.1" 302 -
127.0.0.1 - - [01/Nov/2020 14:33:54] "GET /search/bad HTTP/1.1" 200 -
我考虑过简单地使用表单,但从上面的获取帖子中,搜索中也使用了令牌。我不明白为什么重定向不起作用,它只是坐在搜索页面上。有一个 200 响应/search/bad HTTP/1.1" 200
,但它不会去/重定向到错误的搜索 url。关于如何使重定向起作用的任何想法?
解决方案
If other guys also face that same issue, this is how I solved =>
Python file
flash('some message for index page')
return redirect(url_for('index'))
At Javascript
fetch('url',{
method:'POST'
})
.then((response)=>{
if(response.redirected){
window.location.href = response.url;
}
})
.catch(function(e){
})
So it will load the index page with the message.
推荐阅读
- docker - 重建 Docker 镜像需要时间
- python - 将 Model.Predict 的输出转换为整数
- batch-file - 如何比较批处理文件中的两个时间字符串
- javascript - 如何使用 Web 自定义协议打开 ElectronJS 应用程序?
- python - [Python]_ python 是否有像列表理解一样的字符串理解?
- mediawiki - 如何使用 Pywikibot 和 category.py 移动多个类别?
- c# - 我如何使用用户可能通过的任何比较器实现冒泡排序
- linux - Pine 脚本 - 如何编写检测八个相似连续蜡烛的脚本
- python - 我收到此错误 UnboundLocalError: local variable 'pay' referenced before assignment on line 9 每次请
- bash - 用于从日志文件中获取主机和每个主机的请求总数的 shell 脚本