简体   繁体   English

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

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

I am trying to make my django project to work but somehow I always come to get this error我正在尝试使我的 django 项目正常工作,但不知何故我总是遇到这个错误

Method Not Allowed (POST): /不允许的方法(POST):/

I have tried using decorators like @csrf_exempt like in the django documentation as to not encounter csrf errors and yet I came to this error.Please tell me what's the problem with my code...我曾尝试在django 文档中使用像 @csrf_exempt 这样的装饰器,以免遇到 csrf 错误,但我遇到了这个错误。请告诉我我的代码有什么问题......

urls.py网址.py

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

views.py视图.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应用程序.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主页.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): / - means your function is not accepting post methos it accpets only get or other safe methods. Method Not Allowed (POST): / - 表示您的 function 不接受它只接受 get 的 post 方法或其他安全方法。
you're not changing any state of your database so you don't have to use post request you can use get intead of 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)

and change your urls like this并像这样更改您的网址

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

and in your javascript change method post to get并在您的 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