如何在 DOJO 工具包中进行 ajaxSetup beforeSend 之类的操作,以在 DOJO AJAX POST 中提供 CSRF 令牌
Django 的最新版本要求 csrf_token 与每个 POST 请求一起发送(无论是通过 AJAX 还是通过普通请求)。
他们建议 Django 现在将接受自定义 HTTP 标头 X-CSRFTOKEN 以及表单提交本身中的 CSRF 令牌,以便于与流行的 JavaScript 工具包一起使用,该工具包允许将自定义标头插入到所有 AJAX 请求中。
他们给出了一个在 jQuery 中执行此操作的示例,
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken",
$("#csrfmiddlewaretoken").val());
}
}
});
我无法弄清楚如何在 DOJO 工具包中执行类似的操作。 我已经使用 dojo.rpc.JsonService() 一段时间了。
请建议一种在 DOJO 中做类似事情的方法?
或者唯一的选择是对每个 xhrPost 请求分别执行此操作?
Recent releases of Django require csrf_token to be sent along with each POST request (whether through AJAX or through normal request).
They suggest that, Django will now accept the CSRF token in the custom HTTP header X-CSRFTOKEN, as well as in the form submission itself, for ease of use with popular JavaScript toolkits which allow insertion of custom headers into all AJAX requests.
They give an example to do this in jQuery
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken",
$("#csrfmiddlewaretoken").val());
}
}
});
I am not able to figure out how to do something similar in DOJO toolkit.
I have been using dojo.rpc.JsonService() for a while.
Please suggest a way to do something similar in DOJO?
Or the only option is to do this on each and every xhrPost request separately?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
免责声明:我对 django 不熟悉。
除了扩展基本的 dojo xhr 定义(不推荐它)之外,我想说您可能想要扩展 dojo.xhr 或构建一个实用方法。
实用程序方法将混合或设置传递到 dojo.xhr 的参数的“headers”属性:
myCustomNameSpace.xhr = function (xhrArgs) {
var csrfHeader = { "X-CSRFToken" : dojo.byId(csrfmiddlewaretoken).val(); };
xhrArgs.headers?dojo.mixin(xhrArgs.headers,csrfHeader):xhrArgs.headers=csrfHeader;
dojo.xhrPost(xhrArgs);
};
通过 myCustomNameSpace.xhr({method:"POST",url:"http://www....."}) 调用;
Disclaimer: I'm not familiar with django.
Outside of extending the base dojo xhr definition(wouldn't recommend it), I'd say you may want to extend dojo.xhr or build a utility method.
Utility method would mix in or set the "headers" attribute of the arguments you pass into dojo.xhr :
myCustomNameSpace.xhr = function (xhrArgs) {
var csrfHeader = { "X-CSRFToken" : dojo.byId(csrfmiddlewaretoken).val(); };
xhrArgs.headers?dojo.mixin(xhrArgs.headers,csrfHeader):xhrArgs.headers=csrfHeader;
dojo.xhrPost(xhrArgs);
};
Invoked via myCustomNameSpace.xhr({method:"POST",url:"http://www....."});
{% csrf_token %} 将以如下形式出现:
所以只需像这样混合您的内容:
The {% csrf_token %} will appear in the form just like this:
so just mix your content like this: