PIPIONE
最近刚好做了一个Django+React的Todo程序,也遇到了同样的问题,我的代码如下,供你参考:fromdjango.viewsimportViewfromdjango.httpimportJsonResponse,QueryDictfromdjango.utilsimporttimezonefrom.modelsimportTodoclassTodoView(View):defpost(self,request):form=request.POSTtodo=Todo(content=form['content'],time=timezone.now())todo.save()resp=JsonResponse({'result':'success'})resp['Access-Control-Allow-Origin']='*'returnrespdefget(self,request):todos=Todo.objects.all()resp=JsonResponse({'result':'success','todos':[todo.toJSON()fortodointodos]})resp['Access-Control-Allow-Origin']='*'returnrespclassTodoItemView(View):defdelete(self,request,todo_id):todo=Todo.objects.get(id=todo_id)todo.delete()resp=JsonResponse({'result':'success'})resp['Access-Control-Allow-Origin']='*'returnrespdefput(self,request,todo_id):todo=Todo.objects.get(id=todo_id)put=QueryDict(request.body,encoding=request.encoding)todo.status=put.get('status')todo.save()resp=JsonResponse({'result':'success'})resp['Access-Control-Allow-Origin']='*'returnrespdefget(self,request,todo_id):todo=Todo.objects.get(id=todo_id)resp=JsonResponse({'result':'success','todo':todo.toJSON()})returnrespdefoptions(self,request,todo_id):todo=Todo.objects.get(id=todo_id)resp=JsonResponse({'result':'success'})resp['Access-Control-Allow-Origin']='*'resp['Access-Control-Allow-Methods']='GET,POST,PUT,DELETE,OPTIONS'returnresp