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

你可能感兴趣的:(Django)