我在Typescript中调用内部Web服务进行ajax调用。所有端点都是" GET"正在工作,但是" POST"它说
" 403 Forbidden" - "详细信息:CSRF失败:未设置CSRF cookie"
我试图解决问题的事情:
- 关注https://docs.djangoproject.com/ko/1.11/ref/csrf/
- 尝试删除' django.middleware.csrf.CsrfViewMiddleware'
- 试用@csrf_exempt
这一切都没有奏效,每次都会发生同样的错误。
这是我在Typescript中的代码:
sendMessage(message, receiverId){
let self = this;
var message_obj = "{\"id\":\""+ GUID.generateGUID() +"\",\"message\":\""+ message +"\",\"receiverId\":\""+ receiverId + "\",\"moddate\":\""+ Date.now() +"\"}";
var message_json = JSON.parse(message_obj);
$.ajax({
type: "POST",
url: "/chat/message/",
data:{"message_object":message_json},
credentials: 'same-origin',
success: function (response) {
alert(response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
})
}
这是一个正在运行的ajax调用的示例:
getMessages(){
let self = this;
$.ajax({
type: "GET",
url: "/chat/message/",
dataType: "json",
success: function (response) {
response = JSON.stringify(response);
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
})
}
编辑:
这是我尝试使用csrf_exempt的地方:
URLS.PY
from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt
from chat_api import views
urlpatterns = [
url(r'^message/$', csrf_exempt(views.ChatMessageAPIEndpoint.as_view())),
url(r'^message/(?P<commit>([0-9a-fA-F])+)', csrf_exempt(views.ChatMessageAPIEndpoint.as_view())),
url(r'^devicekey/(?P<devid>([\w+-:])+)', views.DeviceAPIEndpoint.as_view()),
url(r'^devicekey/$', views.DeviceAPIEndpoint.as_view()),
url(r'^contacts/$', views.ContactAPIEndpoint.as_view()),
url(r'^read/$', views.ReadStatusEndpoint.as_view()),
]
VIEWS.PY
@csrf_exempt
@need_post_parameters([PARAM_MESSAGE_OBJ])
def post(self, request, *args, **kwargs):
data = request.POST.get(PARAM_MESSAGE_OBJ)
try:
message_obj = json.loads(data)
except Exception as e:
return HttpResponseBadRequest(error_json("Could not parse JSON"))
...
答案 0 :(得分:0)
我发现了这个错误,我会在这里发布错误:
Views.py 中的我的课程使用&#34; Oauth2APIView&#34; ! 将其更改为&#34;查看&#34; 确实为我解决了问题!