【发布时间】:2011-03-15 20:02:47
【问题描述】:
我有一个 django 应用程序,它公开了一个 API,其 url conf 看起来像这样,
url('^links/', linkhandler),
链接处理程序是一个 django 活塞资源,我在下面给出了它的 POST(Create function),
def create(self, request):
try:
link_obj = Link.objects.get(link = request.POST['link'])
print link_obj
link_obj.rec_count = link_obj.rec_count+ request.POST.get('rec_count', 1)
link_obj.save()
return link_obj
except:
try:
query_obj = Query.objects.get(query_word = request.POST['query'])
print query_obj
except:
query_obj = Query(query_word = request.POST['query'])
query_obj.save()
link_obj = Link(link = request.POST['link'], rec_count = request.POST.get('rec_count', 1), query = query_obj)
link_obj.save()
return link_obj
以上所有内容都很好,当我通过 CURL 发出 POST 请求时,它工作得非常好。 例如,下面是我的 CURL 请求,它有效,
curl -d "query=hp&link=http://www.shopping.hp.com/&rec_count=1" http://localhost:8000/api/links/
但是当我从一个greasemonkey脚本中尝试这个时,它总是返回一个400错误:(
下面是相关的greasemonkey脚本
GM_xmlhttpRequest({
method:"POST",
url:"http://localhost:8000/api/links/",
headers:{
"User-Agent":"Mozilla/5.0",
"Accept":"text/json",
"Content-Type" : "application/x-www-form-urlencoded"
},
data: encodeURI("query="+GM_getValue('q', '')+"&link="+this.previousSibling.href+"&rec_count=1"),
onerror: function errorhand()
{
alert("error occurred!");
}
});
可能是什么问题?
【问题讨论】:
-
您是否检查过
data参数是否正确生成?通过查看服务器日志,curl 和 geasemonkey 版本的请求 url 看起来相同吗? -
您也可以在 Wireshark 中查看两者。我注意到
Accept标头不同。另一种方法是将 cURL 硬编码的 URL 复制到脚本中作为测试。
标签: javascript django firefox greasemonkey django-piston