【问题标题】:Fetch Api giving opaque response even after handling cors while requesting data from FLASK [duplicate]即使在从 FLASK 请求数据时处理 cors 之后,也能获取不透明的响应 [重复]
【发布时间】:2021-06-29 21:33:30
【问题描述】:

尝试了所有方法,但没有响应!我找不到我错的地方!

我在获取请求时遇到了问题。 它与 FLASK localhost 无法正常工作。 我提出了一个简单的获取请求,但我得到的只是登录控制台时的不透明响应。 不过,只需通过 api 端点,我就能看到响应。

.py(烧瓶本地主机)

from flask import Flask, render_template, request, jsonify
from flask_cors import CORS, cross_origin

app = Flask(__name__)

@app.route('/findHotels',methods = ['GET','POST'])
@cross_origin()
def findHotelsHelper():
    if request.method == 'GET':
        response = jsonify(message="Simple server is running")
        response.headers.add("Access-Control-Allow-Origin", "*")
        return response

if __name__ == '__main__':
    app.run(debug = True)

以下是使用 fetch api 请求数据的 html 代码

<!DOCTYPE html>
<html>
<body>
  <h1>Find Nearest Hotels in your Area! </h1>
  
  <form id="form1" action="http://localhost:5000/findHotels" method="GET">
      First name: <input type="text" name="fname"><br>
      Last name: <input type="text" name="lname"><br><br>
      <input type="button" onclick="loadDoc()" value = "GO">
  </form>
  
  <p id="demo"></p>
  
  <script>
  
      
  async function loadDoc(){
      await fetch('http://127.0.0.1:5000/findHotels', { method: 'GET', mode:'no-cors'})
          .then(function (response) {
            console.log(response);
            return response;
          }).then(function (text) {
            console.log('GET response:');
            console.log(text); 
          });
  }
  </script>
  
  </body>
</html>

任何建议将不胜感激。 附言抱歉,我是堆栈溢出的新手,请原谅我这段时间没有遵循适当的帖子规则。 Image showing working get request Image showing failed/(getting opaque) request if using fetch api 另外我想指出,简单的表单也可以正常工作,我能够检索 json 数据,但我想在没有它的情况下仅使用 JS。

【问题讨论】:

  • Access-Control-Allow-Origin 的标头值很奇特 - 我不了解 Python,但值 * 而不是 no-cors 似乎更合适?
  • 好的,很抱歉,它只是'*'。此处打错,已编辑。
  • 在您的 python 代码中,您有 if request.method == 'GET':,但您正在使用 ajax 发送 POST 请求

标签: javascript html flask cors fetch-api


【解决方案1】:

您的fetch 选项中有mode: 'no-cors'。根据https://developer.mozilla.org/en-US/docs/Web/API/Request/mode,它给出了不透明的响应。

由于您的服务器能够发送 CORS 标头,因此您应该设置 mode: 'cors'。

<!DOCTYPE html>
<html>
<body>
  <h1>Find Nearest Hotels in your Area! </h1>
  
  <form id="form1" action="http://localhost:5000/findHotels" method="GET">
      First name: <input type="text" name="fname"><br>
      Last name: <input type="text" name="lname"><br><br>
      <input type="button" onclick="loadDoc()" value = "GO">
  </form>
  
  <p id="demo"></p>
  
  <script>
  
      
  async function loadDoc(){
      await fetch('http://127.0.0.1:5000/findHotels', { method: 'GET', mode:'cors'})
          .then(function (response) {
            console.log(response);
            return response;
          }).then(function (text) {
            console.log('GET response:');
            console.log(text); 
          });
  }
  </script>
  
  </body>
</html>

【讨论】:

  • 好的,我想我应该调查一下,效果太棒了!非常感谢,我会花时间理解基本概念,我只是想通过这段时间,我的错。再次感谢您。
【解决方案2】:

Ajax 请求正在发送 POST 请求,因此您应该更改 Python 代码部分以匹配该方法。

from flask import Flask, render_template, request, jsonify
from flask_cors import CORS, cross_origin

app = Flask(__name__)

@app.route( '/findHotels', methods = ['GET','POST'] )
@cross_origin()
def findHotelsHelper():
    if request.method == 'POST':
        response = jsonify(message="Simple server is running")
        response.headers.add("Access-Control-Allow-Origin", "*")
        return response

if __name__ == '__main__':
    app.run(debug = True)

假设 Python 代码发送纯文本作为响应,那么在 fetch 调用链中,您应该返回文本值 - 即:response.text()

<form name='search' action='http://localhost:5000/findHotels' method='GET'>
    First name: <input type='text' name='fname'><br>
    Last name: <input type='text' name='lname'><br><br>
    <input type='button' value='GO' />
</form>

<p id='demo'></p>

<script>

    async function loadDoc(e){
        await fetch( oForm.action, { method: 'POST', mode:'no-cors' })
            .then( r=>r.text() ) // return the `text()` property
            .then( text=>{
                console.log('GET response:%s',text);
            })
    }
    
    let oForm=document.forms.search;
    let oBttn=oForm.querySelector('input[type="button"]');
        oBttn.addEventListener('click',loadDoc);
    


</script>

没有Python来测试我很快就敲出了上面的一个PHP版本。这工作得很好,所以问题可能出在 Python 代码上?!

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();
        header('Access-Control-Allow-Origin','*');
        $message="Simple server is running";
        exit($message);
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
        <script>
            document.addEventListener('DOMContentLoaded',(e)=>{
            
                async function loadDoc(e){
                    await fetch( oForm.action, { method:'POST', mode:'no-cors' })
                        .then( r=>r.text() ) // return the `text()` property
                        .then( text=>{
                            console.log('POST response:%s',text);
                            alert( text )
                        })
                }
                
                let oForm=document.forms.search;
                let oBttn=oForm.querySelector('input[type="button"]');
                    oBttn.addEventListener('click',loadDoc);
                
            })
        </script>
    </head>
    <body>
        <form name='search' method='GET' action=''>
            First name: <input type='text' name='fname' />
            Last name: <input type='text' name='lname' />
            <input type='button' value='GO' />
        </form>
    </body>
</html>

【讨论】:

  • 是的,它已修复,但又是错字,因为我试图让任何方法起作用。匆忙,我这样做了,但我已经修复了它,尝试编写你提到的确切代码,它仍然在获取时给出不透明的响应,但在浏览器正常获取时工作。谢谢你看的这么仔细。再次对不起。
猜你喜欢
  • 2018-04-12
  • 1970-01-01
  • 1970-01-01
  • 2015-12-02
  • 1970-01-01
  • 2019-12-04
  • 2016-09-16
  • 2017-08-03
  • 1970-01-01
相关资源
最近更新 更多