我正在开发我的第一个 API,到目前为止我已经能够通过 google 寻求帮助,但我陷入了这个困境:
我的 POST 请求在 Postman 上工作正常,但是当我尝试使用 HTML 中的表单发出 POST 请求时,出现以下错误:
Access to fetch at 'http://127.0.0.1:5000/api/v1/units' from origin 'http://localhost:63342' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
index.html:1 Uncaught (in promise) TypeError: Failed to fetch
我的 Flask 应用程序中的方法:
@marshal_with(unit_fields)
def post(self):
args = self.reqparse.parse_args()
unit = models.Unit.create(**args)
return unit, 201, {"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type",
"Location": url_for("resources.units.unit", id=unit.id)}
Vue.js 应用程序中的 fetch 调用:
addUnit: function() {
fetch("http://127.0.0.1:5000/api/v1/units", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: document.querySelector("#unitName").value,
faction: document.querySelector("#unitFaction").value
})
})
}
感谢您提供如何克服它的建议:)
最佳答案
太棒了,谢谢斯蒂芬!它所需要的只是:
from flask_cors import CORS
和
CORS(app, support_credentials=True)
在app.py中!
关于python - POST 上没有 'Access-Control-Allow-Origin' header (Flask API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52996455/