我用python 编写了以下脚本
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app, resources=r'/chat', headers='Content-Type')
@app.route("/chat")
def chat():
print(request)
request.get_data()
data = json.loads(request.data)
response = chatbot.get_response(str(data['message']))
response_data = response.serialize()
response = jsonify({'data': response_data})
return response
app.run(host="0.0.0.0", port=8900, debug=True)
我从运行在上的JavaScript前端调用此APIhttp://localhost:8080
我正在使用谷歌浏览器,并得到以下错误
Access to XMLHttpRequest at 'http://localhost:8900/chat/' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我还在Python控制台中为每个请求获得以下日志消息
127.0.0.1 - - [19/Mar/2020 15:12:00] "?[33mOPTIONS /chat/ HTTP/1.1?[0m" 404 -
我真的很沮丧,因为即使我把代码改成
@app.route("/chat")
def chat():
print(request)
request.get_data()
data = json.loads(request.data)
response = chatbot.get_response(str(data['message']))
response_data = response.serialize()
response = jsonify({'data': response_data})
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'append,delete,entries,foreach,get,has,keys,set,values,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
return response
我仍然会犯同样的错误。
你能试着这样设置标题吗?
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app, resources=r'/chat', headers='Content-Type')
@app.route("/chat")
def chat():
print(request)
request.get_data()
data = json.loads(request.data)
response = chatbot.get_response(str(data['message']))
response_data = response.serialize()
response = jsonify({'data': response_data})
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Headers'] = 'append,delete,entries,foreach,get,has,keys,set,values,Authorization'
response.headers['Access-Control-Allow-Methods'] = 'GET,PUT,POST,DELETE,OPTIONS'
return response
app.run(host="0.0.0.0", port=8900, debug=True)