Fetch Api 即使在从 FLASK 请求数据时处理了 cors 之后也会给出不透明的响应
Fetch Api giving opaque response even after handling cors while requesting data from FLASK
尝试了所有方法,但响应没有通过!我找不到我哪里错了!
我在处理提取请求时遇到了问题。
它在 FLASK 本地主机上无法正常工作。
我提出了一个简单的获取请求,但在登录控制台时我得到的只是一个不透明的响应。
不过,只要继续 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)
以下是 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.S。抱歉,我是堆栈溢出的新手,请原谅我这次没有遵循 post 的正确规则。
Image showing working get request
Image showing failed/(getting opaque) request if using fetch api
另外我想指出,简单的表单也可以正常工作,我能够检索 json 数据,但我想在没有它的情况下仅使用 JS 来完成。
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
调用链中,您应该 return 文本值 - 即: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>
您的 fetch
选项中有 mode: 'no-cors'
。根据 https://developer.mozilla.org/en-US/docs/Web/API/Request/mode 它给出了不透明的响应。
由于您的服务器能够发送 CORS headers,您应该设置 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>
尝试了所有方法,但响应没有通过!我找不到我哪里错了!
我在处理提取请求时遇到了问题。 它在 FLASK 本地主机上无法正常工作。 我提出了一个简单的获取请求,但在登录控制台时我得到的只是一个不透明的响应。 不过,只要继续 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)
以下是 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.S。抱歉,我是堆栈溢出的新手,请原谅我这次没有遵循 post 的正确规则。 Image showing working get request Image showing failed/(getting opaque) request if using fetch api 另外我想指出,简单的表单也可以正常工作,我能够检索 json 数据,但我想在没有它的情况下仅使用 JS 来完成。
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
调用链中,您应该 return 文本值 - 即: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>
您的 fetch
选项中有 mode: 'no-cors'
。根据 https://developer.mozilla.org/en-US/docs/Web/API/Request/mode 它给出了不透明的响应。
由于您的服务器能够发送 CORS headers,您应该设置 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>