我有测试网站在这里。我已经在代码中启用了CORS。
app = Flask (__name__,
static_url_path='',
static_folder='./')
cors = CORS(app,
resources={r"/*":{"origins":"*"}},
cors_allowed_origins="*",
async_mode='threading'
)
socketio = SocketIO(app)
socketio.run(app,port=5000, host='0.0.0.0')
这是一个示例响应:
@app.route('/getobsspecieslist', methods = ['GET'])
#@cross_origin(origin='localhost',headers=['Content- Type','Authorization'])
def resp_obsspecieslist():
response = {}
# Check if user sent a name at all
query = """
select t2.COMMONNAME
from bird_observation_location_date_v3 t1
left join ebird_info_dataset t2 on t2.bird_id = t1.bird_id
group by t2.COMMONNAME
order by t2.COMMONNAME asc
"""
resp = []
res = query_db(query)
for row in res:
resp += [{'name': row[0]}]
response["result"] = resp
response = jsonify(response)
response.headers.add('Access-Control-Allow-Origin', '*')
# Return the response in json format
return response
仍然没有按预期工作。我四处看了看,尝试了多种建议,但都无济于事。请帮助!
===============================================================
进一步检查显示这个错误首先出现:
Error TypeError: NetworkError when attempting to fetch resource. index.js:588:17
SetupSpeciesDropdown http://cocostraws.com/script/index.js:588
(Async: promise callback)
SetupSpeciesDropdown http://cocostraws.com/script/index.js:587
_onload http://cocostraws.com/script/index.js:18
onload http://cocostraws.com/script/index.js:2
(Async: EventHandlerNonNull)
<anonymous> http://cocostraws.com/script/index.js:2
它来自这段代码:
function SetupSpeciesDropdown() {
var url = "http://127.0.0.1:5000/getobsspecieslist"
//var url = "http://www.cocostraws.com/getobsspecieslist"
fetch(url, {mode: 'cors'}).then(res => res.json()).then(function(speciesList) {
d3.select("select#dropdown")
.selectAll('myOptions')
.data(speciesList["result"])
.enter()
.append('option')
.text(function (d) { return d["name"]; }) // text showed in the menu
.attr("value", function (d) { return d["name"]; }); // corresponding value returned by the button
d3.select("select#dropdown").on("change", function(d) {
// recover the option that has been chosen
selectedBird = d3.select(this).property("value");
// run the updateChart function with this selected option
LoadHeatMapData(selectedBird);
});
// Load the map corresponding to the first species in the list.
selectedBird = speciesList["result"][0]["name"];
LoadObsHeatMapData(speciesList["result"][0]["name"]);
})
.catch((error) => {
console.error('Error ', error); /* this is line 588 */
});
};
第588行来自错误处理。它在先前的获取中失败。有人能指出我的错误吗?
资源映射中的正则表达式不正确:r"/*"
匹配0个或多个正斜杠的字符串,您想要r"/.*"
代替。flask_cors
期望regex语法(使用re
包),而不是glob语法。
但是你可能有其他问题。cors_allowed_origins
和async_mode
不是文档中的关键字参数,您不需要response.headers.add('Access-Control-Allow-Origin', '*')
行,这应该由扩展处理。
最后,您需要能够通过凭据吗?如果是这样,请查看supports_credentials
选项的文档…请注意,不能将它与原始*
一起使用,因为它太不安全了。
找到问题。它来自这两行:
var url = "http://127.0.0.1:5000/getobsspecieslist"
//var url = "http://www.cocostraws.com/getobsspecieslist"
问题是,我的网站没有www.
在前面。把它改成这样就解决了问题。
var url = "http://cocostraws.com/getobsspecieslist"
我不知道你是什么使用CORS头,但如果你这样做在前端javascript的AJAX请求,使用CORS头肯定会工作…关于AJAX,请参阅W3schools文档。