axios CSRF失败:来源检查失败-http://localhost:8000/与任何可信来源都不匹配

nkkqxpd9  于 2023-03-08  发布在  iOS
关注(0)|答案(2)|浏览(298)

请帮助我解决这个问题。我正在构建一个由Django Rest Framework和ReactJS组成的应用程序。我使用了ViewSets。
我的错误:enter image description here
Demo
响应数据:

{"detail":"CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins."}

ReactApp中的删除电极导线功能

export const deleteLead = (id) => (dispatch) => {
  axios
    .delete(`/api/leads/${id}/`)
    .then((res) =>
      dispatch({
        type: DELETE_LEAD,
        payload: id,
      })
    )
    .catch((err) => {
      console.log(err);
    });
};

导联视图集:从rest_framework导入视图集,权限从. serializers导入LeadSerializers从销售线索.models导入销售线索

# lead viewset
class LeadViewSet(viewsets.ModelViewSet):
    queryset = Lead.objects.all()
    # permission - bu ruxsat beruvchi
    permission_classes = [
        permissions.AllowAny # barcha uchun ruxsat
    ]
    serializer_class = LeadSerializers

电极导线电极导线:

# lead serializer
class LeadSerializers(serializers.ModelSerializer):
    class Meta:
        model=Lead
        fields="__all__"

电极导线型号:

class Lead(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField(max_length=100, unique=True)
    message = models.TextField(max_length=500, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name
euoag5mw

euoag5mw1#

尝试在设置文件中设置CSRF受信任来源、允许的主机和,如下所示

CSRF_TRUSTED_ORIGINS = [
    'http://localhost:8000'
],
ALLOWED_HOSTS = [
    'localhost',
],
CORS_ORIGIN_WHITELIST = [
    'http://localhost:8000',
]
dgiusagp

dgiusagp2#

除了Jaime所写的内容之外,我还有以下内容:

python manage.py shell <<EOF
from django.conf import settings
from urllib.parse import urlparse

print([urlparse(origin).netloc.lstrip("*") for origin in settings.CSRF_TRUSTED_ORIGINS])
print({origin for origin in settings.CSRF_TRUSTED_ORIGINS if "*" not in origin})
EOF

运行上述命令将显示 CSRF_TRUSTED_ORIGINS 的集合详细信息。
我有一种情况,我是正确的,但后来,在设置文件下面的某个地方,这个相同的设置引用了一个 localhost:7007,而且它已经部署了。
以上内容帮助我检测并修复了它。如果您的应用位于Docker容器中,请将其启动为:
docker exec -i在此处添加容器名称pythonmanage.pyshell
并且其其它部分将保持与上面所示的相同。
a sample of the error page on deployment

相关问题