首页 > 解决方案 > 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。关于如何使重定向起作用的任何想法?

标签: javascriptpythonflaskredirectfetch

解决方案


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.


推荐阅读