python - POST 上没有 'Access-Control-Allow-Origin' header (Flask API)

标签 python post vue.js flask fetch

我正在开发我的第一个 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/

相关文章:

vue.js - 可以在 vue.js 应用程序中排除 `this` 关键字吗?

python - re.sub() 负向后看 + 负向前看

python装饰器提取参数

python - 将信息从 html 传递给 python

Python如何计算两个日期之间的天数?

javascript - AJAX POST 和加号 (+) -- 如何编码?

java - 如何以一定的间隔发送 HTTPClient post 消息

ios - 如何在 iOS 中以 url 的形式发布数据?

javascript - 如何直接从组件访问 Vue 的路由数组?

javascript - Vue-Router 仅适用于某些路由