【问题标题】:CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted originsCSRF 失败:来源检查失败 - http://localhost:8000/ 不匹配任何受信任的来源
【发布时间】:2022-01-06 19:14:23
【问题描述】:

请帮我解决问题。 我正在构建一个由 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 中的 DeleteLead 函数

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

LeadViewSet: 从 rest_framework 导入视图集,权限 从 .serializsers 导入 LeadSerializers 从leads.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

LeadSerzializers:

# 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

【问题讨论】:

    标签: reactjs axios permissions csrf-token django-rest-viewsets


    【解决方案1】:

    尝试像这样在设置文件中设置您的 CSRF 可信来源、允许的主机和设置文件

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

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 2022-07-06
      • 1970-01-01
      • 2019-04-11
      • 2016-12-19
      • 2015-04-30
      • 2018-04-21
      • 2020-06-03
      • 2022-01-04
      相关资源
      最近更新 更多