【发布时间】:2019-03-30 11:45:28
【问题描述】:
我正在开发我的第一个 API,到目前为止,我已经能够通过 google 寻求帮助,但我被困在这个 API 上:
我的 POST 请求在 Postman 上运行良好,但是当我尝试在我的 HTML 中使用表单来发出 POST 请求时,我收到以下错误:
从源“http://localhost:63342”获取“http://127.0.0.1:5000/api/v1/units”的访问权限已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
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
})
})
}
感谢您对如何克服它的任何建议:)
【问题讨论】:
-
你可能想看看这篇文章,他们建议使用flask-cors。 stackoverflow.com/q/28461001/6511985
标签: python post vue.js flask fetch