当前位置: 首页 > 知识库问答 >
问题:

获取API提供不透明的响应,即使在处理cors,同时从FLASK请求数据[重复]

孟永望
2023-03-14

什么都试过了,但是没有得到回应!我找不到我错在哪里!

我在处理抓取请求时遇到问题。它完全不能与FLASK本地主机正常工作。我放了一个简单的get请求,但我得到的只是在控制台上登录时的不透明响应。不过,只需在 api endpoint上,我就能够看到响应。

。py(flask localhost)

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)

下面是html的代码,它使用fetch api请求数据

<!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>

如有任何建议,将不胜感激。P、 对不起,我是新来的堆栈溢出,请原谅我在这段时间没有遵守适当的规则。图像显示工作get请求图像显示失败/(变得不透明)请求如果使用fetch api我想指出,简单表单也工作正常,我能够检索json数据,但我想不使用它,只使用JS。

共有2个答案

司迪
2023-03-14

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代码发送纯文本作为响应,那么在获取调用链中,您应该返回文本值 - 即: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>
海叶秋
2023-03-14

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

由于您的服务器能够发送 CORS 标头,因此应设置模式:“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>
 类似资料:
  • 我使用的API根据成功/失败有不同的json响应。它们不是HTTP错误,而是json主体中的代码。 我添加了一个,但感觉我只是把事情放在一起,忽略了问题。这是一种可接受的或“pythonic”的方式来处理类似的不同响应吗?另外,如果存在状态,我是否正确地使用来跳过该行?

  • 问题内容: 究竟是通过对吗? 我的应用程序处理了来自用户的输入,并且花了一些时间。在这段时间内,应用程序无法处理其他请求。我已经测试了我的应用程序,它可以让我同时处理多个请求。 问题答案: 从Flask 1.0开始,Flask随附的WSGI服务器默认在线程模式下运行。 在1.0之前的版本中,或者如果你禁用线程,则服务器以单线程模式运行,并且一次只能处理一个请求。任何并行请求都必须等待,直到可以处理

  • 我读了这个问题和这个问题。前者只解释“无源”与“同源”;后者建议“no-cors”不有用,因为响应不透明(Javascript无法读取/执行任何有用的操作): 有人能告诉我们,在这些“有限的情况”中,我们想要使用“no-cors”的例子是什么吗(尽管反应是不透明的?) 我能想到的唯一情况是一种单向交流;如果客户机向服务器发送GET或POST就足够了,那么服务器就可以跟踪请求的发生;(例如,增加请求

  • 我已经编写了一个flask api,它使用request.form累加post请求params。API在postman中表现完美,但在axios请求中失败。

  • 我是iOS和Swift的新手,我正在尝试使用AlamoFire3.4.0来做一个web请求。当我的请求成功时,一切都很好。但是,如果我的请求失败,服务器将返回300或更大的状态代码,以及响应体中的一些JSON,其中包含关于请求失败原因的更多信息。例如,我正在与之交谈的API要求对每个请求进行身份验证。如果身份验证由于某种原因失败,我将返回401,响应体中的JSON将为: 我发出此请求的代码如下所示

  • 我正在使用rest服务获取我的react原生android应用程序的响应。每当我使用localhost(我尝试使用127.0.0.1)和端口8080,但fetch给了我[TypeError:Network request failed]。在没有本地主机的情况下,获取请求工作正常。当与邮递员一起使用时,Rest服务可以正常工作。 我正在使用expo运行我的代码。以及使用Maven实现后端依赖性。 我