Flask API 在删除方法中出现 CORS 错误

发布于 2025-01-10 08:28:31 字数 1856 浏览 0 评论 0原文

我在 Flask 中开发了一个 Rest api。当我用邮递员测试它们时,我的所有 api 端点都工作正常。

现在,我正在使用 Javascript 开发一个应用程序,该应用程序会消耗我的 api 资源。

我在使用与删除方法一起使用的端点时遇到问题。具有 get 和 post 的端点工作正常,但删除方法则不行。我收到下一个 CORS 错误:

Access to fetch at 'http://localhost:5000/contacto' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

这是我的 Javascript 代码:

let data ={id: id};
let url = "http://localhost:5000/contacto";
fetch(url, {
    credentials: 'include',
    method: 'DELETE',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
})
.then(res => res.json())
.then(res => {
    alert(res.result);
});

在服务器端,我使用flask_cors。我使用以下代码配置应用程序:

from flask import Flask, jsonify, request
from flask_cors import CORS

import controllers.userController as userController

app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
#CORS(app)
#CORS(app, resources={r"/*": {"origins": "*"}}, send_wildcard=True)
 CORS(app, resources={r"/*": {"origins": "http://127.0.0.1:5500"}}) 

带有删除方法的服务的路径是这样的:

@app.route('/contacto', methods = ['DELETE'])
def deleteContacto():
  parametros = request.args
  id = parametros['id']
  result = contactController.eliminar_contacto(id)

 response = None
if result == True:
    response = jsonify({'result':'Contacto eliminado con éxito'})
else:
    response = jsonify({'result':'Error al eliminar el contacto'})
response.headers.add('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
return response

我需要一些帮助。我搜索并尝试了许多可能的解决方案,但它们对我不起作用。我有点绝望了。

预先感谢并致以问候。

I have developed a rest api in Flask. All my api endpoints work fine when I test them with postman.

Now, I am developing an application with Javascript that consumes the resources of my api.

I'm having trouble consuming an endpoint that works with the delete method. Endpoints with get and post work fine, but not the delete method. I get the next CORS error:

Access to fetch at 'http://localhost:5000/contacto' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

This is my Javascript code:

let data ={id: id};
let url = "http://localhost:5000/contacto";
fetch(url, {
    credentials: 'include',
    method: 'DELETE',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
})
.then(res => res.json())
.then(res => {
    alert(res.result);
});

On the server side, I use flask_cors. I configure the app with this code:

from flask import Flask, jsonify, request
from flask_cors import CORS

import controllers.userController as userController

app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
#CORS(app)
#CORS(app, resources={r"/*": {"origins": "*"}}, send_wildcard=True)
 CORS(app, resources={r"/*": {"origins": "http://127.0.0.1:5500"}}) 

The path of my service with delete method is this:

@app.route('/contacto', methods = ['DELETE'])
def deleteContacto():
  parametros = request.args
  id = parametros['id']
  result = contactController.eliminar_contacto(id)

 response = None
if result == True:
    response = jsonify({'result':'Contacto eliminado con éxito'})
else:
    response = jsonify({'result':'Error al eliminar el contacto'})
response.headers.add('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
return response

I need some help. I have searched and tried many possible solutions but they do not work for me. I'm a bit desperate.

Thanks in advance and regards.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

掩于岁月 2025-01-17 08:28:31

我的做法有点不同,但请确保将此选项设置为允许删除和选项方法:

'Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS'

我手动将它们添加到 Flask CORS 中的响应对象中

resp.headers.add('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')

,应该将其设置为默认值,但也许有些配置错误?
请参阅文档:
https://flask-cors.readthedocs.io/en/latest/configuration。 html

I do this a bit different, but make sure you have this option set to allow delete and options methods:

'Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS'

I add them manually to the response object in flask

resp.headers.add('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')

CORS should be setting this as a default, but maybe something is misconfigured?
see the docs:
https://flask-cors.readthedocs.io/en/latest/configuration.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文