0

Im trying to create a new model with a rest api using Django Rest Framework.

This is my serializer:

class FooSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Foo

This is my view.py

@api_view(['POST', 'GET','DELETE','OPTIONS'])
def foos(request):
    """
    API endpoint to create, delete and get foos
    """
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)

    model = Foo
    serializer_class = FooSerializer

    if request.method == "POST":
        data = JSONParser().parse(request)
        serializer = FooSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        else:
            return JSONResponse(serializer.errors, status=400)

    return Response(serializer.data)

Then in my backbone view:

       foo = new Foo
            name:'Bla di bla di'
        foo.save()

Noting happens except for the OPTIONS to fail, there is no POST.

failing OPTIONS

OPTIONS http://127.0.0.1:8080/api/foo/  

I dont know what to do, this does not happen if I leave out the contentType:"application/json" part of the post (when doing a manual post)

It works with CURL in my terminal.

In my chrome Inspector > Network I get this:

Request URL:http://127.0.0.1:8080/api/foo/
Request Headersview source
Access-Control-Request-Headers:accept, origin, authorization, content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Origin:http://localhost:8000
Pragma:no-cache

Request, and Response is empty.

EDIT

I turned of the server with the Rest APi and the exact same thing happens! So this tels me one thing, its not anything to do with the server. Must be the AJAX stuff.

Im completely confused :-(

Harry
  • 13,091
  • 29
  • 107
  • 167

1 Answers1

1

When doing a cross-domain request, it's normal to do an OPTIONS call before doing a POST.

If the OPTIONS call happens, but no POST follows, most likely cause of is CORs failure.

Check the server response - is it returning the correct headers?

You need 3:

'Access-Control-Allow-Origin' 'Access-Control-Allow-Methods'
'Access-Control-Allow-Headers'

These must match your request.

See this answer for quick fix: https://stackoverflow.com/a/3520073

Or this page for background + full explanation : http://www.html5rocks.com/en/tutorials/cors/

Community
  • 1
  • 1
Lucidity
  • 1,299
  • 17
  • 19