目前我有一个搜索页面,它接受输入,然后使用它来搜索 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
然后用于搜索并返回结果。我需要使用 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
但它不会转到/重定向到错误的搜索网址。关于如何使重定向发挥作用有什么想法吗?
服务器重定向不是浏览器重定向。重定向只会导致 fetch/curl 请求新的 url(如果已配置,如curl 中的
-F
)
使用类似的东西怎么样?
如果搜索“无效”,服务器将返回 statusCode 400。 在客户端上,如果搜索响应的状态为 400,则
window.location.href = '/search/bad'
我们可以使用真实的
<form>
通过浏览器提交真实的http POST(而不是通过fetch或任何js客户端)。在这种情况下,浏览器将跟随重定向。
如果其他人也面临同样的问题,这就是我解决的方法=>
Python 文件
flash('some message for index page')
return redirect(url_for('index'))
在 JavaScript
fetch('url',{
method:'POST'
})
.then((response)=>{
if(response.redirected){
window.location.href = response.url;
}
})
.catch(function(e){
})
因此它将加载带有消息的索引页面。
调整@lwin的答案(你让我找到了正确的方向,所以谢谢!),这对我来说不起作用。
response.redirected
不是由该 return 语句设置的,而且我看不到任何其他内容被传递给 JS 来指示重定向的位置。相反,我必须传递一个响应对象来告诉 JS 去哪里。就我而言,我使用重定向来显示错误消息,并且我需要继续执行重定向函数,以便在该页面上显示适当的信息。
Python 文件
redirect(url_for('index'))
response = {'redirect': 'index'}
return make_response(response, 200)
JS文件
fetch('url', {
method: "POST",
})
.then(function(response) {
if (response.status != 200) {
// handle error...
return;
}
response.json().then(function(data) {
if (data.redirect) {
window.location.href = data.redirect;
}
});
})
.catch(function(e) {
});