django在接受post請求時顯示403forbidden

在測試Django的時候發現一個問題,就是按照一般教程設置好URL的mapping之後,使用get請求總能得到正確的迴應,但是在使用post請求時,卻根本無法得到請求,會顯示403forbidden:

Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Forbidden (CSRF cookie not set.): /
[23/Mar/2017 20:58:36] "POST / HTTP/1.1" 403 2857

根據提示(CSRF cookie not set)上網搜索了一下,發現只要在接收post請求的函數前加上csrf_exempt裝飾器就可以了:

# coding=utf-8

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json


# Create your views here.
@csrf_exempt
def index(request):
    if request.method == 'POST':
        body = json.loads(request.body)
        print body['value']
        return HttpResponse(request.body)

控制檯輸出爲(傳入的body爲{'value': 'test'}):

Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
test
[23/Mar/2017 21:03:37] "POST / HTTP/1.1" 200 17
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章