【问题标题】:No 'Access-Control-Allow-Origin' header on POST (Flask API) [duplicate]POST(Flask API)上没有“Access-Control-Allow-Origin”标头[重复]
【发布时间】: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
           })
       })
   }

感谢您对如何克服它的任何建议:)

【问题讨论】:

标签: python post vue.js flask fetch


【解决方案1】:

太棒了,谢谢斯蒂芬!它所需要的只是:

from flask_cors import CORS

CORS(app, support_credentials=True)

在 app.py 中!

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-08-12
  • 2016-01-21
  • 1970-01-01
  • 2016-05-13
  • 2023-03-03
  • 2017-09-19
  • 2015-04-02
  • 2020-10-24
相关资源
最近更新 更多