首页 > 解决方案 > 获取“不允许的方法:/users/update_contact/”

问题描述

这是我的 javascript 函数旨在更新我的数据库。但是,我收到两个错误:

  1. 不允许的方法:/users/update_contact/"
  2. SyntaxError: JSON.parse: JSON 数据的第 1 行第 1 列的数据意外结束

最后,我的数据库没有更新。

下面是调用函数的按钮:

<button onclick="update_contact()" class="update_contact">Update Contact Info</button>

Django视图:

class UserContactUpdate(View):

    model = Contact
    fields = ["github_profile_link", "phone_number", "email_address"]
    git = "https://www.github.com/"

    def get_object(self):
        return get_object_or_404(Contact)

    def get_success_url(self):
        return reverse("users:view_profile")

    def post(self, request, *args, **kwargs):
        contact = self.get_object()
        contact.github_profile_link = self.git + request.POST['github_username']
        contact.mobile_number = request.POST['mobile_number']
        contact.email_address = request.POST['email']
        contact.save()
        print ("contact link is" + contact.github_profile_link,
                "mobile number is" + contact.mobile_number,
                "email adress is " + contact.email_address)
        return HttpResponse("contact saved")

update_contact = UserContactUpdate.as_view()     

Django 网址:

path('update_contact/', view=update_contact, name="update_contact"),

function update_contact (){
    url = "{% url 'users:update_contact' %}"; 

    git_profile = prompt("enter git profile name")
    phone = prompt("enter phone number")
    email = prompt("enter email address")

    const contact = {
        "git_profile" : git_profile,
        "phone_number" : phone,
        "email" : email 
    };  
  var stringify_contact = JSON.stringify(contact);

    const options = {
        method: 'POST',
        body: JSON.parse(stringify_contact),
    mode: 'same-origin',
    dataType: 'json',
        headers : {
            'content-Type' : 'application/json',
            'X-CSRFToken': csrftoken,
            }
        }

    fetch(url, options)
        .then(res => res.json())
        .then(res => console.log(res))
}

标签: javascriptdjango

解决方案


你为什么要JSON.parse处理你的 JSON 字符串?请求正文应该有 JSON 字符串而不是 javascript 对象。所以,改变

 const options = {
        method: 'POST',
        body: JSON.parse(stringify_contact),
        mode: 'same-origin',
        dataType: 'json',
        headers : {
            'content-Type' : 'application/json',
            'X-CSRFToken': csrftoken,
            }
        }

 const options = {
        method: 'POST',
        body: stringify_contact,
        mode: 'same-origin',
        dataType: 'json',
        headers : {
            'content-Type' : 'application/json',
            'X-CSRFToken': csrftoken,
            }
        }

至于您的其他关于 Method not allowed 的问题,您可以先尝试上述方法,看看是否会再次出现?另外,您在服务器上收到请求的方法是什么?您可以使用浏览器中的开发工具进行检查。


推荐阅读