简体   繁体   English

dojo /请求PUT方法不起作用

[英]dojo/request PUT method dosn't work

I have a web app using Python Django and Dojo framework. 我有一个使用Python Django和Dojo框架的Web应用程序。 I wanna send a PUT request from Dojo (using dojo/request) to server Django but when server receives a request, the data within are empty and validate Invalid. 我想从Dojo(使用dojo /请求)向服务器Django发送PUT请求,但是当服务器收到请求时,其中的数据为空并验证无效。 BUT when I change method from PUT to POST, it's work correctly. 但是当我将方法从PUT更改为POST时,它正常工作。

Here is my code: 这是我的代码:

_save: function(data){
        var idForm = "editForm" + this.id;
        var value = dijit.byId(idForm).get('value');
        console.log(value);
        request.put("/api/guestbook/"+this.bookName+"/greeting/"+this.id+"/", {
            data: {
                book_name: this.bookName,
                message: value.message
            },
            headers: { "X-CSRFToken": _cookie('csrftoken') }
        }).then(lang.hitch(this, function(text){

        }));
    },

And in Django: 在Django:

def put(self, request, *args, **kwargs):
    form = self.get_form(self.form_class)
    logging.warning(form)
    logging.warning(request.PUT)
    if form.is_valid():
        logging.warning("This form is VALID")
    else:
        logging.warning("This form is INVALID!!!")

Anyone can help me? 有人可以帮帮我吗? Thanks for help! 感谢帮助!

I found the way to receive PUT method below: 我找到了接收PUT方法的方法如下:

def put(self, request, *args, **kwargs):
    request.PUT = QueryDict(request.body)
    form = self.form_class(request.PUT)
    if form.is_valid():
        logging.warning("This form is VALID")
    else:
        logging.warning("This form is INVALID")

This is ok :) 还行吧 :)

Thanks all! 谢谢大家!

I'm guessing from your X-CSRFToken header that you are doing cross domain requests, ie CORS . 我猜你的X-CSRFToken标题是你在做跨域请求,即CORS

If you look in your browser's console, you'll probably see an OPTIONS request being sent to the server. 如果您查看浏览器的控制台,您可能会看到OPTIONS请求被发送到服务器。 This is called a "preflight request", and your server needs to respond with CORS headers telling the browser that it's okay to make the cross domain PUT request. 这称为“预检请求”,您的服务器需要使用CORS标头进行响应,告诉浏览器可以进行跨域PUT请求。

In your case, you want the server to respond with headers similar to: 在您的情况下,您希望服务器使用类似于以下内容的标头进行响应:

Access-Control-Allow-Origin: http://your-site-hostname-and-port
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-CSRFToken

Simple POST requests do not need the preflight OPTIONS request, that's probably why it works. 简单的POST请求不需要预检OPTIONS请求,这可能就是它的工作原因。 A pretty good tutorial on html5rocks here . 在html5rocks是一个非常不错的教程在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM