Why do I get loose closing brackets for my Django

2019-07-20 18:46发布

问题:

Here's my JSON response for http://localhost:8000/characters/api/users/1?format=json

)]}',
{"id":1,"username":"admin","mage_by_user":[3],"mage_last_updated":"2015-02-11T16:13:16.229Z"}

Notice the )]}', on the first line.

Here is my code that gets called to create the JSON:

class UserSerializer(serializers.ModelSerializer):
    mage_by_user = serializers.PrimaryKeyRelatedField(
        many=True, queryset=Mage.objects.all())
    mage_last_updated = serializers.ReadOnlyField(
        source='mage_by_user.updated_date')

    class Meta:
        model = User
        fields = ('id', 'username', 'mage_by_user', 'mage_last_updated',)

Further testing:

  • I've noticed the title of the page is TypeError at <insert url here>.
  • This happens with all of my endpoints
  • If I try to access a non-existent object (userId=2 for instance), then renders 'normally' for DRF, e.g:

    {
    detail: "Not found"
    }

Any idea why this would happen?

回答1:

Those characters are inserted by the Djangular middleware AngularJsonVulnerabilityMiddleware, to inject Json Vulnerability Protection

A JSON vulnerability allows third party website to turn your JSON resource URL into JSONP request under some conditions. To counter this your server can prefix all JSON requests with following string ")]}',\n". Angular will automatically strip the prefix before processing it as JSON.

Unfortunately, it means it breaks various JSON viewers.



回答2:

Sorry to not be more help, but this looks like something entirely unrelated to REST framework. There's absolutely no way a JSON response there would ever be rendered in that way.

Perhaps you have a custom renderer configured, that's outputting a malformed response, perhaps you have some broken middleware inserting those characters, perhaps its an issue in the client or whatever environment you're making the requests, or perhaps it's something else entirely unrelated to any of those.

I'd start by trying to narrow down the issue as much as possible - remove all the complexity from the view and serializer and attempt to replicate the behavior in a test case.

Most likely there's some sort of unexpected integration issue you're missing or some otherwise obvious code typo that's being overlooked.