在django-rest框架中使用GET methoid将url作为参数传递?

时间:2015-10-23 06:09:20

标签: ajax django rest xmlhttprequest django-rest-framework

我将把一个url作为GET参数传递给restful API,但是它与url模式不匹配,因此404返回。

我使用django-rest框架作为服务器端。

以下是urls.py

url(r'^method/?P<url>(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))$',views.Method.as_view()), name='method'),

客户端xhr代码是这样的。

var xhr = new XMLHttpRequest();
// url is like https://storage.googleapis.com/xxx/cccc/abc.txt
xhr.open('GET', 'method/' + url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
    if (this.status == 200) {
        // do something
    }
};
xhr.send();

正则表达式没问题,但服务器仍然返回404。

即使我将请求网址传递给

xhr.open('GET', 'method?=' + url, true);

仍然无法找到404。

这样做的正确方法是什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

更改您的客户端xhr代码,如:

var xhr = new XMLHttpRequest();
var url = 'https://storage.googleapis.com/xxx/cccc/abc.txt';
xhr.open('GET', 'method/?url=' + encodeURIComponent(url), true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
    if (this.status == 200) {
        // do something
    }
};
xhr.send();