簡體   English   中英

如何停止獲取 405 錯誤方法不允許?

[英]How to stop Getting 405 error Method not allowed?

我正在嘗試使我的 django 項目正常工作,但不知何故我總是遇到這個錯誤

不允許的方法(POST):/

我曾嘗試在django 文檔中使用像 @csrf_exempt 這樣的裝飾器,以免遇到 csrf 錯誤,但我遇到了這個錯誤。請告訴我我的代碼有什么問題......

網址.py

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

視圖.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)

應用程序.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 = '' }); }

主頁.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): / - 表示您的 function 不接受它只接受 get 的 post 方法或其他安全方法。
您不會更改數據庫的任何 state,因此您不必使用發布請求,您可以使用 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 更改方法帖子中獲取

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM