如何停止获取 405 错误方法不允许?

How to stop Getting 405 error Method not allowed?

我正在尝试让我的 django 项目正常工作,但不知何故我总是遇到这个错误

Method Not Allowed (POST): /

我试过在 django documentation 中使用像 @csrf_exempt 这样的装饰器来避免遇到 csrf 错误,但我遇到了这个 error.Please 告诉我我的代码有什么问题...

urls.py

from test.views import HomePageView,predict    
urlpatterns = [ 
path('', HomePageView.as_view(), name="homepage"),
path('predict', predict, name="predict"),]

views.py

class HomePageView(Notif, TemplateView):
    template_name = "homepage.html"

    def predict(self, request, *args, **kwargs):
     if request == 'POST':
        text = self.request.get_json().get('message')
        # check if text is valid
        response = get_response(text)
        message = {'answer': response}
        return JsonResponse(message)

    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(HomePageView, self).dispatch(*args, **kwargs)

app.js

onSendButton(chatbox) {
        var textField = chatbox.querySelector('input');
        let text1 = textField.value
        if (text1 === "") {
            return;
        }

        let msg1 = { name: "User", message: text1 }
        this.messages.push(msg1);

        fetch( $SCRIPT_ROOT+'/predict',{
            method: 'POST',
            body: JSON.stringify({ message: text1 }),
            mode: 'same-origin',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'X-CSRFToken':csrftoken,
            },
          })
          .then(r => r.json())
          .then(r => {
            let msg2 = { name: "Sam", message: r.answer };
            this.messages.push(msg2);
            this.updateChatText(chatbox)
            textField.value = ''

        }).catch((error) => {
            console.error('Error:', error);
            this.updateChatText(chatbox)
            textField.value = ''
          });
    }

homepage.html

<div class="container">
    {% csrf_token %}
    <div class="chatbox">
        <div class="chatbox__support">
            <div class="chatbox__header">
                <div class="chatbox__image--header">
                    <img src="https://img.icons8.com/color/48/000000/circled-user-female-skin-type-5--v1.png" alt="image">
                </div>
                <div class="chatbox__content--header">
                    <h4 class="chatbox__heading--header">Chat support</h4>
                    <p class="chatbox__description--header">Hi. My name is Sam. How can I help you?</p>
                </div>
            </div>
            <div class="chatbox__messages">
                <div></div>
            </div>
            <div class="chatbox__footer">
                <input type="text" placeholder="Write a message...">
                <button class="chatbox__send--footer send__button">Send</button>
            </div>
        </div>
        <div class="chatbox__button">
            <button class="btn-light"><img src="./images/chatbox-icon.svg" width="45px" height="45px"/></button>
        </div>
    </div>
</div>
<script type="text/javascript">
 $SCRIPT_ROOT='{{ request.path }}'
</script>

Method Not Allowed (POST): / - 表示您的函数不接受 post 它只接受 get 或其他安全的方法方法。
您没有更改数据库的任何状态,因此您不必使用 post 请求,您可以使用 get intead of post

class HomePageView(Notif, TemplateView):
    template_name = "homepage.html"

    @staticmethod
    def predict(self, request, *args, **kwargs):
        if request == "POST":
            text = self.request.get_json().get("message")
            # check if text is valid
        response = get_response(text)
        message = {"answer": response}
        return JsonResponse(message)

    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(HomePageView, self).dispatch(*args, **kwargs)

并像这样更改您的网址

urlpatterns = [ 
    path('predict', HomePageView.predict, name="predict"),
]

并在您的 javascript 中更改方法 post 以获取

fetch($SCRIPT_ROOT + '/predict', {
    method: 'GET',
    body: JSON.stringify({
        message: text1
    }),
    mode: 'same-origin',
})