在React+Django项目中发送POST请求时出现403 Forbidden Error

9udxz4iz  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(147)

我正在尝试做一个网站,我正在将React前端集成到Django后端。我正试图从我的前端发送一个帖子请求到后端。如果我在端口3000和8000上分别运行前端和后端,我不会得到错误,我的请求会失败。但是当它们在同一个端口(7000)上运行时,我得到了403禁止错误。
如果我让我的视图@csrf_exempt,那么我得到一个500(内部服务器错误)。
下面是我的frontend:

const handleSubmit = async (formData) => {
        try {
            const response = await axios.post('http://127.0.0.1:7000/backend/api/create_message/', formData);
            console.log('Message sent successfully:', response.data);

        } catch (error) {
            console.error('Error sending message:', error);
        }
    };

以下是我的views.py:

@api_view(['POST', 'GET'])
def create_message(request):
    if request.method == 'POST':
        serializer = MessageSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()

            # Send mail
            name = request.POST.get('name')
            phone = request.POST.get('phone')
            email = request.POST.get('email')
            message = request.POST.get('message')

            subject = "Contact Form"
            content = f"Name: {name} \n" \
                      f"Phone: {phone}\n" \
                      f"Email: {email}\n" \
                      f"Message: {message}"
           
            from_mail = settings.EMAIL_HOST_USER
            recipient_list = ['email']
            send_mail(subject, content, from_mail, recipient_list, fail_silently=False)
            messages.success(request, "Message successfully sent", extra_tags='success')
            form = MessageForm()
            context = {'form': form}
            template = '../templates/lpadj/message_form.html'
            return render(request, template, context)

        messages.warning(request, "Message not sent", extra_tags='warning')
        form = MessageForm()
        context = {'form': form}
        template = '../templates/lpadj/message_form.html'
        return render(request, template, context)

    else:
        form = MessageForm()
        context = {'form': form}
        template = '../templates/lpadj/message_form.html'
        return render(request, template, context)

该项目的urls.py:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('backend/', include('lpadj.urls')),
    re_path(r"^(?:.*)?$", TemplateView.as_view(template_name="index.html"))
]

该应用程序的urls.py:

path("", views.index, name="landingPage"),
    re_path(r"^api/newsletter/subscribe/$", views.newsletter_subscribe, name="newsletter_signup"),
    re_path(r"^api/newsletter/unsubscribe/$", views.newsletter_unsubscribe, name="newsletter_unsubscribe"),
    re_path(r"^control/newsletter/$", views.control_newsletter, name="control_newsletter"),
    re_path(r"^control/newsletter-list/$", views.control_newsletter_list, name="control_newsletter_list"),
    re_path(r'^api/create_message/$', views.create_message, name='create_message'),

另见settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'lpadj.apps.LpadjConfig',
    'rest_framework',
    'corsheaders',
]
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
]
CORS_ALLOW_ALL_ORIGINS: True
ROOT_URLCONF = 'landingpageappdjango.urls'

我试着用网址和搜索,但到目前为止还没有工作。如果我在端口3000和8000上分别运行前端和后端,我不会得到错误,我的请求会失败。但是当它们在同一个端口(7000)上运行时,我得到了403禁止错误。如果我让我的视图@csrf_exempt,那么我得到一个500(内部服务器错误)。

uhry853o

uhry853o1#

原因可能与CsrfViewMiddleware有关。尝试禁用它并检查它将如何工作。
//“django.middleware.csrf.CsrfViewMiddleware”,"main.middleware.DisableCSRFMiddleware"
class DisableCSRFMiddleware(object):

def __init__(self, get_response):
    self.get_response = get_response

def __call__(self, request):
    setattr(request, "_dont_enforce_csrf_checks", True)
    response = self.get_response(request)
    return response

相关问题